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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
输入一个整数,计算其各位之和,如此迭代直到和为个位数。
思路:int转string—— int to_string(int) 函数
int addDigits(int num) {
int sum=num;
while(sum>=10)
{
string str = to_string(sum);
sum=0;
for(int i=0;i<str.size();i++)
sum+=int(str[i]-'0');
}
return sum;
}
挑战:不用循环实现
int
addDigits
(
int
num
)
{
return 1 + (
num
- 1) % 9;
}