Skip to content

Commit 5c25f88

Browse files
Added Day-26 Solution
1 parent 6a8add1 commit 5c25f88

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Day-26_Add_Digits.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
'''
2+
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
3+
4+
Example:
5+
6+
Input: 38
7+
Output: 2
8+
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
9+
Since 2 has only one digit, return it.
10+
Follow up:
11+
Could you do it without any loop/recursion in O(1) runtime?
12+
13+
Hide Hint #1
14+
A naive implementation of the above process is trivial. Could you come up with other methods?
15+
Hide Hint #2
16+
What are all the possible results?
17+
Hide Hint #3
18+
How do they occur, periodically or randomly?
19+
Hide Hint #4
20+
You may find this Wikipedia article useful.
21+
22+
'''
23+
24+
class Solution(object):
25+
def addDigits(self, num):
26+
while num>9:
27+
res = 0
28+
for i in str(num):
29+
res+=int(i)
30+
num = res
31+
return num

0 commit comments

Comments
 (0)