给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?
class Solution {
public:
// method 1:
int addDigits1(int num){
while(num >= 10){
num = num/10 + (num%10);
}
return num;
}
// method 2:
int addDigits2(int num){
if(num < 10){
return num;
}else if(num%9 == 0){
return 9;
}else{
return num%9;
}
}
int addDigits(int num) {
// return addDigits1(num); // accepted
return addDigits2(num); // accepted
}
};leetcode 258. 各位相加(Add Digits)
原文:https://www.cnblogs.com/zhanzq/p/10571803.html