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
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 an integer which has a fixed upper limit. For example, the largest unsigned 64-bit integer is
2^64 - 1 = 18,446,744,073,709,551,615
. This is 20 total digits, so your Big O will actually be constant time O(1) because it can't grow arbitrarily large.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.