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 int addDigits(int num) {
int gewei;
int shiwei;
int hehge;
int shishi;
hehge = num%10;
shishi = num/10;
int ans=0;
int tmp;
tmp = num;
if(num <10) {
return num;
}
if(shishi*10 == num) {
// System.out.println("asd");
return shishi;
}else {
while (tmp !=0) {
gewei = num%10;
shiwei = num/10;
ans = gewei + shiwei;
num = ans;
tmp = num/10;
}
return ans;
}
}