Here's the recursive solution:
function sum_of_digits(n)
if n < 10 then
return n
return (n mod 10) + sum_of_digits(n / 10)
Try tracing sum_of_digits(1234) yourself. What's the first call? When do you stop? You compute , which becomes , then , and finally .
Time complexity: since you process one digit per call.
Space complexity: for the call stack.