Recursion · Digits · Base case

Sum of Digits Visualizer

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

Base case When n < 10, there is nothing left to peel. Return n.
Recursive case digit_sum(n) = n % 10 + digit_sum(n // 10). The tree is a single chain, one call shorter each time.

Recursion tree

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

def digit_sum(n):
if n < 10:
return n
return n % 10 + digit_sum(n // 10)

Complexity

PieceCostWhy
TimeO(digits)One call per digit, which is O(log n).
StackO(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)