Sum of digits (recursion)
Easy TimeO(d) for d digits SpaceO(d) for d digits
Given a whole number n, zero or greater, return the sum of its decimal digits — for 12345 that is 1 + 2 + 3 + 4 + 5, 15. The number is not turned into text, and a single-digit number is its own digit sum.
Examples
Example 1
- Input
- n = 12345
- Output
151 + 2 + 3 + 4 + 5 = 15.
Example 2
- Input
- n = 1000
- Output
11 + 0 + 0 + 0 = 1— the zeros carry no weight of their own.
The Code
function sumDigits(n) {
if (n < 10) return n;
return (n % 10) + sumDigits(Math.floor(n / 10));
}
sumDigits(12345);Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Power Raise a number to a power one multiply at a time.
- Mutual recursion Two functions that call each other all the way down.