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
15
1 + 2 + 3 + 4 + 5 = 15.

Example 2

Input
n = 1000
Output
1
1 + 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
Step through sumDigits(12345) call by call