[leetcode]258.Add Digits

题目

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

Example:

Input: 38
Output: 2
Explanation: 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 res = num;
        while(res / 10 != 0) {
            num = res;
            res = 0;
            while(num != 0) {
                res += num % 10;
                num /= 10;
            }
        }
        return res;
    }
}

解法二

思路

我们来观察1到20的规律:
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 1
11 2
12 3
13 4
14 5
15 6
16 7
17 8
18 9
19 1
20 2
根据上面的枚举,我们可以发现,每9个数一个循环,所以我们直接对9取余即可,但是9对9取余为0,所以我们稍作调整即可,用(n-1)%9+1即可。

代码

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

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9789144.html