[LeetCode] Add Digits

Add Digits

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

解題思路:

解法一:

模擬法,不斷將數字拆分然後相加,直到只有一位數。

class Solution {
public:
    int addDigits(int num) {
        while(num/10>0){
            int sum = 0;
            while(num!=0){
                sum += num%10;
                num = num/10;
            }
            num = sum;
        }
        return num;
    }
};
解法二:

題目要求沒有遞歸,沒有循環,且時間複雜度爲O(1)。那就找規律。

~input: 0 1 2 3 4 ...
output: 0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 ....
注意到,後面都是1-9不斷循環。

有兩個公式:

d(n) = num%9 == 0 ? (num==0? 0 : 9) : num%9

d(n) = 1 + (n-1) % 9

因此代碼如下:

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

class Solution {
public:
    int addDigits(int num) {
        return num%9 == 0? (num==0?0:9) : num%9;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章