Skip to content

Commit 3b69fc4

Browse files
committed
upload 1 answer, Aug 16th
1 parent 9fe072d commit 3b69fc4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Easy/AddDigits.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
3+
4+
For example:
5+
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
6+
7+
Follow up:
8+
Could you do it without any loop/recursion in O(1) runtime?
9+
10+
Hint:
11+
A naive implementation of the above process is trivial. Could you come up with other methods?
12+
What are all the possible results?
13+
How do they occur, periodically or randomly?
14+
You may find this Wikipedia article(https://en.wikipedia.org/wiki/Digital_root) useful
15+
*/
16+
17+
public class AddDigits {
18+
public int addDigits(int num) {
19+
String str = String.valueOf(num);
20+
while(str.length()>1){
21+
num =0;
22+
for(int i =0;i<str.length();i++){
23+
num += str.charAt(i)-'0';
24+
}
25+
str = String.valueOf(num);
26+
}
27+
return num;
28+
}
29+
}
30+
31+
/*
32+
Reference:
33+
https://leetcode.com/discuss/52140/share-my-simple-to-understand-no-tricky-java-solution
34+
https://leetcode.com/discuss/52092/256ms-java-one-line-solution
35+
*/

0 commit comments

Comments
 (0)