Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

各位相加

来源Leetcode第258题

给定一个非负整数 num,反复将各个位上的数字相加,直到结果为一位数。

示例:

1
2
3
输入: 38
输出: 2
解释: 各位相加的过程为:3 + 8 = 11, 1 + 1 = 2。 由于 2 是一位数,所以返回 2。

进阶:
你可以不使用循环或者递归,且在 O(1) 时间复杂度内解决这个问题吗?


暴力

按照题意暴力运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int addDigits(int num) {
while(num/10>0){
num = add(num);
}
return num;
}
private int add(int x){
int res=0;
while(x>0){
res+=x%10;
x/=10;
}
return res;
}

取余

X = 100*a + 10*b + c = 99*a + 9*b + (a+b+c);所以对9取余即可。

但是要注意当X是9的倍数时,即(a+b+c)也是9的倍数,这时候返回9即可,因为只要是9的倍数,其各位相加一定为9,否则返回X % 9.

1
2
3
public int addDigits(int num) {
return num < 10 ? num : (num % 9 == 0 ? 9 : num % 9);
}

大佬的精简代码

    public int addDigits(int num) {
        return (num-1)%9+1;
    }