【问题描述】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】
public static int addDigits1(int num) {
while (num / 10 > 0) {
int result = 0;
int temp = num;
while (temp != 0) {
result += (temp % 10);
temp /= 10;
}
num = result;
}
return num;
}
【解法2】
public static int addDights2(int num) {
while (num >= 10) {
num = num/10 + num % 10;
}
return num;
}
【解法3——找规律】
<span style="white-space:pre"> </span>public static int addDights3(int num) {
return 1 + (num - 1) % 9;
}