forked from szl0072/Leetcode-Solution-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddDigits.java
58 lines (51 loc) · 1.02 KB
/
AddDigits.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package leetcode;
/**
* Created by Edward on 25/07/2017.
*/
public class AddDigits {
/**
* 258. Add Digits
* Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
time : O(1);
space : O(1):
* @param num
* @return
*/
public static int addDigits1(int num) {
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
if (sum > 10) {
return addDigits1(sum);
} else {
return sum;
}
}
public static int addDigits2(int num) {
return (num - 1) % 9 + 1;
}
}