Skip to content

Commit 4e4ea5a

Browse files
committedJul 27, 2020
🚀 27-Jul-2020
1 parent 32c3df0 commit 4e4ea5a

File tree

2 files changed

+110
-0
lines changed

2 files changed

+110
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
2+
3+
Example:
4+
5+
Input: 38
6+
Output: 2
7+
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
8+
Since 2 has only one digit, return it.
9+
Follow up:
10+
Could you do it without any loop/recursion in O(1) runtime?
11+
12+
Hide Hint #1
13+
A naive implementation of the above process is trivial. Could you come up with other methods?
14+
Hide Hint #2
15+
What are all the possible results?
16+
Hide Hint #3
17+
How do they occur, periodically or randomly?
18+
Hide Hint #4
19+
You may find this Wikipedia article useful.
20+
21+
22+
23+
24+
25+
26+
27+
28+
29+
class Solution {
30+
public:
31+
int addDigits(int num) {
32+
int digitalRoot = 0;
33+
while (num > 0) {
34+
digitalRoot += num % 10;
35+
num = num / 10;
36+
37+
if (num == 0 && digitalRoot > 9) {
38+
num = digitalRoot;
39+
digitalRoot = 0;
40+
}
41+
}
42+
return digitalRoot;
43+
}
44+
};
45+
46+
47+
48+
49+
50+
51+
52+
class Solution {
53+
public:
54+
int addDigits(int num) {
55+
if (num == 0) return 0;
56+
if (num % 9 == 0) return 9;
57+
return num % 9;
58+
}
59+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
2+
3+
Example:
4+
5+
Input: 38
6+
Output: 2
7+
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
8+
Since 2 has only one digit, return it.
9+
Follow up:
10+
Could you do it without any loop/recursion in O(1) runtime?
11+
12+
13+
14+
15+
16+
17+
18+
19+
20+
21+
class Solution {
22+
public:
23+
int addDigits(int num) {
24+
int digitalRoot = 0;
25+
while (num > 0) {
26+
digitalRoot += num % 10;
27+
num = num / 10;
28+
29+
if (num == 0 && digitalRoot > 9) {
30+
num = digitalRoot;
31+
digitalRoot = 0;
32+
}
33+
}
34+
return digitalRoot;
35+
}
36+
};
37+
38+
39+
40+
41+
42+
43+
44+
class Solution {
45+
public:
46+
int addDigits(int num) {
47+
if (num == 0) return 0;
48+
if (num % 9 == 0) return 9;
49+
return num % 9;
50+
}
51+
};

0 commit comments

Comments
 (0)