Sum of Digits Recursively
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
4 + 8 + 2 = 14.
9 + 0 + 0 + 1 = 10.
A one-digit number is already its own digit sum.
Algorithm Flow

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:
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:
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.
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
