盒子
盒子

Leetcode-AddDigits

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.
第一次顺着例子写:

public final static int addDigits(int num) {
int a = num%10;
int b = (num-a)/10;
int sum = a+b;

while((sum%10)!=sum){
int c = sum%10;
int d = (sum-c)/10;
sum = c+d;
}
return sum;

}

太繁琐,在discuss看到一种写法:

public final static int addDigits(int num) {
return (num-1)%9+1;
}