Sum Digits
Given a positive integer as an input, write a function sumDigits that calculates the sum of all the digits of this number.
There is one constraint: you cannot convert the input number to another data type.
Breakdown
Approach and test strategy
A decreasing numeric subproblem with a consistent zero case
Read the approach, boundary cases, and complexity
For the lesson's nonnegative integer domain, separate the final decimal digit from the remaining prefix. Add that digit to the result for the prefix. Integer division must remove the digit rather than retain a fractional remainder. The zero case terminates the process and contributes zero. Negative-number handling would require a separate contract, especially for fixed-width minimum values.
Cases to check
- Zero returns zero and a single digit returns itself.
- For 123 the answer is six.
- Use internal and trailing zeros, such as 50201 and 200, so digit removal cannot skip the remaining prefix.
Cost model
Processing d decimal digits takes O(d) steps under fixed-width arithmetic. An iterative implementation uses constant auxiliary state; straightforward recursion retains O(d) frames.
Programming languages for this lesson
Starter code and reference implementations are available in:
The editor shows which of these languages can run on this deployment.
Validate My Answer
If we could convert the input integer to a string or another data structure that was iteratable, it would be easy to walk through each digit and add them together. Now you need to be a little more creative.
The input is a single integer, so think about what actually grows as it gets larger: its number of digits. For example, the largest unsigned 64-bit integer is
2^64 - 1 = 18,446,744,073,709,551,615, which has 20 total digits. Your Big O will be in terms of the number of digits O(d), not the value of the integer.You can solve this iteratively or recursively. In either case, you will likely need to modulo
%and divide by 10.
Sum Digits
Given a positive integer as an input, write a function sumDigits that calculates the sum of all the digits of this number.
There is one constraint: you cannot convert the input number to another data type.