Sum of digits
Warm-up · Write code · about 8 min
Return the sum of the decimal digits of n, using recursion. For example, 472 gives 4 + 7 + 2 = 13.
The last digit is n % 10 and the rest of the number is n / 10 rounded down.
Example 1
Input:
[472]
Output:
13
2 + sumDigits(47) = 2 + 11 = 13.
Example 2
Input:
[9]
Output:
9
One digit is the base case.
Constraints
- 0 ≤ n ≤ 10^9
Learn the idea first: Recursion: base case, recursive case, the call stack, a visual lesson.
More Recursion: base case, recursive case, the call stack problems
- Factorial trace Warm-up
- Missing base case Standard
- Countdown Standard
- Follow the frames of fact(4) Standard
- Print 1..n without loops Challenge