Code Logo

Sum of Digits Recursively

Published at19 Apr 2026
Easy 0 views
Like0

This problem asks you to break a number into smaller pieces until only one digit is left. You are given a non-negative integer n, and your task is to find the sum of all digits in that number.

For example, if n = 482, the digit sum is 4 + 8 + 2 = 14. If n = 9001, the answer is 9 + 0 + 0 + 1 = 10.

This problem works nicely with recursion because one step can separate the last digit from the rest of the number. The last digit can be found with MOD 10. The remaining front part can be obtained by removing that last digit and shifting the number one decimal place to the right.

So the task is to keep taking the last digit, add it to the sum of the remaining digits, and stop when the number has only one digit left.

Example Input & Output

Example 1
Input
n = 482
Output
14
Explanation

4 + 8 + 2 = 14.

Example 2
Input
n = 9001
Output
10
Explanation

9 + 0 + 0 + 1 = 10.

Example 3
Input
n = 7
Output
7
Explanation

A one-digit number is already its own digit sum.

Algorithm Flow

Recommendation Algorithm Flow for Sum of Digits Recursively
Recommendation Algorithm Flow for Sum of Digits Recursively

Solution Approach

A recursive approach comes from splitting the number into two parts: the last digit and the rest of the number.

The last digit is:

n MOD 10

To remove that digit, subtract it from n and divide the result by 10. That gives the remaining front part of the number.

If n is already smaller than 10, then it has only one digit, so the answer is just n. That is the base case.

Otherwise, compute the smaller number first, then combine it with the last digit:

last <- n MOD 10 rest <- (n - last) / 10 return last + sum_digits(rest)

For example, 482 becomes 2 + sum_digits(48), then 8 + sum_digits(4), and finally 4. Putting those together gives 14.

The algorithm is: read n, call the recursive function, and print the result. The number of recursive calls is proportional to the number of digits, so the running time is O(d) where d is the digit count.

Best Answers

Solutions Coming Soon

Verified best solutions for this Challenge are still being analyzed and will be available soon.