【题目描述】
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;
}
};