Sum of Digits
Given a non-negative integer n, return the sum of its decimal digits. For example the digits of 1234 sum to 1 + 2 + 3 + 4 = 10. Return the single integer sum. Solve it recursively, peeling one digit at a time.
- 0 <= n <= 10⁹
- n is an integer
- A single-digit n (0–9) is its own digit sum
n = 00n = 77n = 123410n = 40812We want the sum of a number's digits: 1234 → 1 + 2 + 3 + 4 = 10. This looks like it needs a loop over characters, but there is a cleaner recursive view that reuses exactly the skeleton from Factorial — one call per step, combine on the way back up. That single-call shape has a name: linear recursion.
The two tools for taking a number apart digit by digit are arithmetic, not string conversion:
n % 10 gives the last digit (1234 % 10 = 4).n // 10 (integer division) removes the last digit (1234 // 10 = 123).So the sum of the digits of 1234 is 4 plus the sum of the digits of 123. In general, digitSum(n) = (n % 10) + digitSum(n // 10). The answer for n is built from the answer for a strictly smaller number (one digit shorter) — the recursive signal again.
Recall the skeleton from Factorial: base case, progress, combine. Fill it in:
n // 10 chops off a digit, so each call is strictly smaller and marches toward the single-digit base.n % 10 to whatever the smaller call returns.def sum_digits(n):
if n < 10: # base case: one digit left
return n
return (n % 10) + sum_digits(n // 10)n < 10, not n == 0. Both eventually terminate, but n < 10 stops one step earlier and, more importantly, it directly states the real base fact — a single digit is its own sum. Using n == 0 also works (a lone digit d becomes d + sum_digits(0) = d + 0) but it relies on the quieter fact that the digits of 0 sum to 0; either is fine as long as it is a true stopping fact the recursion is guaranteed to reach.Notice this is linear recursion: each call makes exactly one recursive call, so the call stack goes straight down to a depth equal to the number of digits and then straight back up — no branching. That keeps it to O(d) time and O(d) stack space, where d is the digit count (at most 10 for values up to 10⁹).
Linear recursion is the simplest recursive shape and the one to master first: a single chain of calls, work combined on the return trip, cost proportional to the depth. Any "process one element, then handle the rest" problem — summing a list, reversing a string, walking a linked list — fits this mold. The moment a function needs to make two calls instead of one, the straight chain becomes a tree, the cost can explode, and we are in the world of the next problem, Fibonacci.