Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference of digits at alternate indices in JavaScript
In JavaScript, we can calculate the difference between the sum of digits at even indices and the sum of digits at odd indices. This is useful for various mathematical operations and data validation scenarios.
Problem Statement
We need to write a JavaScript function that takes a number and returns the absolute difference between the sum of digits at even positions and the sum of digits at odd positions (counting from right to left, starting at index 0).
Example
For the number 123456:
- Even indices (0, 2, 4): digits 6, 4, 2 ? sum = 12
- Odd indices (1, 3, 5): digits 5, 3, 1 ? sum = 9
- Difference: |12 - 9| = 3
Using Recursive Approach
const num = 123456;
const alternateDifference = (num, res = 0, ind = 0) => {
if(num){
if(ind % 2 === 0){
res += num % 10;
}else{
res -= num % 10;
};
return alternateDifference(Math.floor(num / 10), res, ++ind);
};
return Math.abs(res);
};
console.log(alternateDifference(num));
3
Using Iterative Approach
Here's an alternative iterative solution that's easier to understand:
function alternateDifferenceIterative(num) {
let evenSum = 0;
let oddSum = 0;
let index = 0;
while (num > 0) {
let digit = num % 10;
if (index % 2 === 0) {
evenSum += digit;
} else {
oddSum += digit;
}
num = Math.floor(num / 10);
index++;
}
return Math.abs(evenSum - oddSum);
}
console.log(alternateDifferenceIterative(123456));
console.log(alternateDifferenceIterative(987654));
console.log(alternateDifferenceIterative(11111));
3 3 1
How It Works
The algorithm processes digits from right to left:
- Extract the last digit using modulo operator (num % 10)
- Add to even sum if index is even, odd sum if index is odd
- Remove the last digit by dividing by 10 and flooring
- Increment index and repeat until no digits remain
- Return absolute difference between the two sums
Comparison
| Approach | Readability | Performance | Memory Usage |
|---|---|---|---|
| Recursive | Compact but complex | Good | Higher (call stack) |
| Iterative | Clear and explicit | Good | Lower (no stack) |
Conclusion
Both approaches effectively calculate the difference of digits at alternate indices. The iterative method is more readable and memory-efficient, while the recursive approach is more compact but harder to debug.
