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.
题意: 依次将数的每一位相加(①),若结果不为个位数,则再次执行第一步,直到结果为个位数.
思路:这道题思路简单
int addDigits(int num) {
int addNum = 0;
while( 0 != num )
{
addNum += num%10;
addNum = addNum%10 + addNum/10;
num /= 10;
}
return addNum;
}
还有更简单的方法,如下,只是我还没想明白为何.
int addDigits(int num) {
return (num - 1)%9 + 1;
}