您的位置:首页 > 其它

[leetCode]Add Digits

2016-01-13 19:31 267 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: