Sum of Digits via Recursion

Easy ⏱ 8 min 76% acceptance ★★★★☆ 4.2
Implement digit_sum(n) that recursively sums the decimal digits of a non-negative integer n, without converting n to a string.

Examples

Example 1
Input
digit_sum(1234)
Output
10
Explanation

1 + 2 + 3 + 4 = 10.

Example 2
Input
digit_sum(7)
Output
7
Explanation

Single digit is its own base case.

Constraints

  • n >= 0
  • No string conversion — use // and % arithmetic.

Topics

RecursionMath

Companies

FlipkartAccenture

Hints

Hint 1

Base case: n < 10, return n.

Hint 2

Recursive case: n % 10 + digit_sum(n // 10).

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.