【题目描述】
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 sum=0;
if(num<=9) return num;
sum=getsum(num);
while(sum>=10){
sum=getsum(sum);
}
return sum;
}
int getsum(int n){
int ans=0;
while(n){
ans+=n%10;
n=n/10;
}
return ans;
}
};在discuss里看到一种纯数学的方法,可惜并米有效率高点还是要耗时8ms。。不过贴上去借鉴一下。。
class Solution {
public:
int addDigits(int num) {
return (num - 1) % 9 + 1;
}
};
本文介绍了一种数字压缩算法,通过不断累加整数的每一位数字直至结果为一位数。提供了两种实现方式:一种是循环累加直到结果小于10;另一种是使用数学公式直接计算结果。
164

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



