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
Selected Reading
Find even odd index digit difference - JavaScript
We are required to write a JavaScript function that takes in a number and returns the difference of the sums of the digits at even place and the digits at odd place.
Understanding the Problem
Given a number, we need to:
- Sum all digits at even positions (0, 2, 4, ...)
- Sum all digits at odd positions (1, 3, 5, ...)
- Return the absolute difference between these sums
Example
For the number 345336:
- Position 0: 6 (even)
- Position 1: 3 (odd)
- Position 2: 3 (even)
- Position 3: 5 (odd)
- Position 4: 4 (even)
- Position 5: 3 (odd)
Even sum: 6 + 3 + 4 = 13
Odd sum: 3 + 5 + 3 = 11
Difference: |13 - 11| = 2
Using Recursive Approach
const num = 345336;
const evenOddDifference = (num, res = 0, ind = 0) => {
if(num){
if(ind % 2 === 0){
res += num % 10;
}else{
res -= num % 10;
}
return evenOddDifference(Math.floor(num / 10), res, ind + 1);
}
return Math.abs(res);
};
console.log(evenOddDifference(num));
2
Using String Conversion Method
const evenOddDifferenceString = (num) => {
const digits = num.toString().split('').reverse();
let evenSum = 0;
let oddSum = 0;
for(let i = 0; i
2
2
Comparison
| Method | Space Complexity | Readability | Performance |
|---|---|---|---|
| Recursive | O(log n) | Moderate | Good |
| String Conversion | O(log n) | High | Good |
Conclusion
Both methods effectively calculate the difference between even and odd positioned digits. The string method is more readable, while the recursive approach demonstrates functional programming concepts.
Advertisements
