-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddDigits.java
More file actions
70 lines (55 loc) · 1.41 KB
/
AddDigits.java
File metadata and controls
70 lines (55 loc) · 1.41 KB
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
59
60
61
62
63
64
65
66
67
68
way 1. while loop 224ms O(n^2)
public class Solution {
public int addDigits(int num) {
if( num < 10 ){ return num ; }
int digitSum= getDigitSum( num );
while(digitSum >=10 ){
digitSum = getDigitSum( digitSum );
}
return digitSum ;
}
private int getDigitSum( int num ){
int reminder=0;
while( num >= 10 ){
reminder += num%10;
num= num/10;
}
return num+reminder;
}
}
9/ 25 /2015
public class Solution {
public int addDigits(int num) {
if( num < 10 ){ return num; }
int temp=0 ;
while( num >=10 ){
temp+= num%10;
num/=10;
}
int rst= temp+ num;
if( rst >= 10 ){
rst= addDigits(rst );
}
return rst;
}
}
Discussion : https://leetcode.com/discuss/59588/my-simple-java-solution-use-loop-and-without-loop
Wiki: https://en.wikipedia.org/wiki/Digital_root
public class Solution {
public int addDigits(int num) {
int result= 0;
if( num < 10 ){ return num; }
while( num >=10 ){
result += num % 10 ;
num/=10;
}
return addDigits( result+num );
}
}
// amazing .....
public class Solution {
public int addDigits(int num) {
// Wiki
return num-9*((num-1)/9);
}
}