Good morning! Here's our prompt for today.
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:
SNIPPET
1// start with 49
24 + 9 = 13
3
4// since the previous addition was 13,
5// move onto summing 13's digits
61 + 3 = 4
We would then return 4
.
Constraints
- Input will be in the range between
0
and1000000000
- Expected time complexity :
O(log n)
- Expected space complexity :
O(1)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
29
import functools
​
​
def sum_digits(num):
# fill in
return num
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert sum_digits(1) == 1
print("PASSED: `sum_digits(1)` should return `1`")
​
def test_2(self):
assert sum_digits(49) == 4
print("PASSED: `sum_digits(49)` should return `4`")
​
def test_3(self):
assert sum_digits(439230) == 3
print("PASSED: `sum_digits(439230)` should return `3`")
​
​
if __name__ == "__main__":
unittest.main(verbosity=2)
print("Nice job, 3/3 tests passed!")
​
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.