EasyFoundational
Sum of Digits
- Time limit
- 1 s
- Memory limit
- 128 MB
- Estimated
- 8 min
- Recursion Fundamentals
Description
Write a recursive function that returns the sum of the decimal digits of a non-negative integer n.
Define it recursively as:
sumOfDigits(0) = 0sumOfDigits(n) = (n % 10) + sumOfDigits(n / 10)forn > 0
Example: n = 1234 returns 10, because 1 + 2 + 3 + 4 = 10.
Do not convert n to a string and iterate over its characters; peel off digits using integer division and modulo inside the recursive calls.
Constraints
0 <= n <= 1000000000
Sample cases
3Sample 1
Input
n = 0
Expected output
0
Sample 2
Input
n = 7
Expected output
7
Sample 3
Skills and languages
Concepts
- Recursion
- Number Bases and Digit Manipulation
Languages
- Python 3
Solve this problem
Create a free account to write, run and submit your solution.
- Write Python or Java in the browser, with your draft saved as you type
- Run your code on the examples as often as you like
- Submit to a sandboxed judge and see exactly which case failed
- Ask the AI mentor for a hint without being handed the answer