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.
class Solution {
public:
int addDigits(int num) {
int ans = 0;
while(num/10 != 0)
{
ans += num % 10;
num /= 10;
if(num/10 == 0)
{
ans += num;
num = ans;
ans = 0;
}
}
return num;
}
};Follow up:
Could you do it without any loop/recursion in O(1) runtime?
int solution1(int num){
return (num - 1) % 9 + 1;
}
class Solution {
public:
int addDigits(int num) {
return num==0?0:(num%9==0?9:(num%9));
}
};
本文介绍了一种将非负整数不断累加其各个位上的数字直至结果仅剩一位数的算法。通过两种方法实现:一种使用循环,另一种则采用数学公式在O(1)时间内解决。此外,还探讨了如何避免使用循环或递归。
279

被折叠的 条评论
为什么被折叠?



