Community

Ask A Question


Notifications
Subscribe You’re not receiving notifications from this thread.

Sum Digits Until One

Here is the interview question prompt, presented for reference.

We're provided a positive integer num. Can you write a method to repeatedly add all of its digits until the result has only one digit?

Here's an example: if the input was 49, we'd go through the following steps:

``` // start with 49 4 + 9 = 13

// move onto 13 1 + 3 = 4 ```

We would then return 4.

Constraints

  • Input will be in the range between -2147483648 and 2147483647
  • Expected time complexity : O(log n)
  • Expected space complexity : O(1)

You can see the full challenge with visuals at this link.

Challenges • Asked 11 months ago by Danaila Marian

jch2Xer Commented on Aug 01, 2019:

This is called the digital room problem or This is called the digital **root* problem?Great job on this site by the way, I am enjoying it! thank you!!

Jake from AlgoDaily Commented on Oct 03, 2019:

Definitely digital root :-) Glad you're enjoying it!

Danaila Marian Commented on Feb 11, 2020:

Hi, guys!
I have a question about "Sum Digits Until One" problem. When I run the code for all the test cases everything is perfect, but when I click 'RUN TESTS' button, it gives me an error:

4
('An error occurred!', NameError("name 'assertEqual' is not defined",))
('An error occurred!', NameError("name 'assertEqual' is not defined",))
('An error occurred!', NameError("name 'assertEqual' is not defined",))

Here is the code:

def sumDigits(n):
if n < 10:
return n
else :
s = 0
while (n > 0):
s += n % 10
n //= 10
return sumDigits(s)
print(sumDigits(49))

Some thoughts about what is wrong?

Al Commented on May 22, 2020:

Same problem here

Anonymous Commented on Sep 18, 2020:

The assertions in the tests for this are incorrect. For example, I am seeing the following: assert sum_digits(49) == 4

It should be sum_digits(49) == 13

Jake from AlgoDaily Commented on Sep 18, 2020:

This is incorrect. The question states "write a method to REPEATEDLY add all of its digits until the result has only one digit". You can see in the example that we later add 1 + 3 from 13 to get 4.