File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments