What is Sum of Digits
Return the sum of the decimal digits of n. The last digit is n % 10. The number that remains is n // 10.
Example. 4321 returns 10, because 4 + 3 + 2 + 1 = 10. A one-digit number returns itself, and 0 returns 0.
Input: 4321 Output: 10
Constraints. 0 ≤ n ≤ 1018. This picture draws at most 8 digits so the chain stays readable.
Approach
n < 10, there is nothing left to peel. Return n.digit_sum(n) = n % 10 + digit_sum(n // 10). The tree is a single chain, one call shorter each time.Recursion tree
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(digits) | One call per digit, which is O(log n). |
| Stack | O(digits) | The chain waits until the base case returns. |
Implementation
def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)