Dynamic Programming21 sections · 916 units
Open in Course

Sum of Digits - Problem Statement

New application

Given a positive integer nn, find the sum of its digits. For example, if n=1234n = 1234, the answer is 1+2+3+4=101 + 2 + 3 + 4 = 10. You will use recursion.

The key point: you can split nn into its last digit (nmod10n \bmod 10) and the remaining digits (n/10\lfloor n / 10 \rfloor). Then the sum is last digit plus the sum of the rest. This gives you a natural recursive structure. Before reading the solution, try to identify the base case yourself. When is the answer obvious without recursion?

unnamed (9) (1).jpg