Problems › Recursion

Sum of Digits

Difficulty: Easy · Topic: Recursion

Given a non-negative integer n, return the sum of its decimal digits. Try expressing it recursively: the last digit plus the digit-sum of the rest.

Examples

sum_digits(123)
→ 6

1 + 2 + 3.

sum_digits(0)
→ 0
sum_digits(9)
→ 9

Target complexity: time O(log n), space O(log n)

Write your solution in Python and run it against hidden tests right on this page. Progressive hints and Python + C++ reference solutions are included.

Learn the idea first: the lesson for this problem.

More Recursion problems