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
Reduce sum of digits recursively down to a one-digit number JavaScript
We have to write a function that takes in a number and keeps adding its digits until the result is a one-digit number. When we have a one-digit number, we return it.
The code uses a recursive function that keeps adding digits until the number is between -9 and 9. We handle the sign separately to avoid duplicating logic.
How It Works
The algorithm follows these steps:
- Take the absolute value of the number to handle sign separately
- If the number is greater than 9, split it into digits and sum them
- Recursively call the function with the new sum
- When we get a single digit, apply the original sign and return
Example
const sumRecursively = (n, isNegative = n < 0) => {
n = Math.abs(n);
if(n > 9){
return sumRecursively(parseInt(String(n).split("").reduce((acc,val) => {
return acc + +val;
}, 0)), isNegative);
}
return !isNegative ? n : n*-1;
};
console.log(sumRecursively(88)); // 8+8=16, 1+6=7
console.log(sumRecursively(18)); // 1+8=9
console.log(sumRecursively(-345)); // 3+4+5=12, 1+2=3, then apply negative
console.log(sumRecursively(6565)); // 6+5+6+5=22, 2+2=4
7 9 -3 4
Alternative Approach Using Math Formula
For positive numbers, there's a mathematical shortcut using modulo 9:
const digitalRoot = (n) => {
if (n === 0) return 0;
if (n < 0) return -digitalRoot(-n);
return 1 + (n - 1) % 9;
};
console.log(digitalRoot(88)); // 7
console.log(digitalRoot(18)); // 9
console.log(digitalRoot(-345)); // -3
console.log(digitalRoot(6565)); // 4
7 9 -3 4
Comparison
| Method | Time Complexity | Readability | Handles Negatives |
|---|---|---|---|
| Recursive Sum | O(log n) | Clear logic | Yes |
| Math Formula | O(1) | Less obvious | Yes |
Conclusion
Both approaches work well for reducing numbers to single digits. The recursive method is more intuitive, while the mathematical formula is more efficient for large numbers.
Advertisements
