【题目】
给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
来源:leetcode
链接:https://leetcode-cn.com/problems/add-digits/
【示例1】
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。由于 2 是一位数,所以返回 2
【进阶】
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
【代码】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :5.9 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int addDigit(int num){
int sum=0;
while(num){
sum+=(num%10);
num/=10;
}
return sum;
}
int addDigits(int num) {
while(num>9)
num=addDigit(num);
return num;
}
};
【规律法】
执行用时 :0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗 :5.8 MB, 在所有 C++ 提交中击败了100.00%的用户
【思想】num=100a+10b+c;abc分别是百位十位个位上的数字,设sum=a+b+c;
num-sum=num-(a+b+c)=100a+10b+c-(a+b+c)=99a+9b=temp,显而易见temp%9=(99a+9b)%9=0=(num-sum)%9=num%9=sum%9
class Solution {
public:
int addDigits(int num) {
if(num>9){
num=num%9;
if(num==0)
return 9;
}
return num;
}
};