Course launching August 2020
Follow me on YouTube for free coding interview videos.
Users who sign up for the email list will receive an exclusive 75% discount at launch.
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.
sumDigits(11) // 1 + 1 = 2 sumDigits(123) // 1 + 2 + 3 = 6 sumDigits(5510) // 5 + 5 + 1 + 0 = 11
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.