LeetCode(43) 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 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
題目要求對一個非負數的各個數位上的數字求和 ,直到最終和為一個個位數為止。
解題思路與程式碼
本題最簡單的方法就是根據題目的意思進行迴圈操作,直到最終得到的數字只有一位為止。
class Solution {
public:
int sumOfDigits(int num)
{
int sum = 0;
while(num)
{
sum += num % 10;
num = num / 10;
}
return sum;
}
int addDigits(int num) {
while(num / 10 != 0)
{
num = sumOfDigits(num);
}
return num;
}
};
解法進階
在LeetCode上我們可以看到本題的提示:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this
這裡wiki上對本問題的數學解法進行了討論,我們不按照這個也可以使用之前的程式碼得到的計算結果去尋找一些規律。這裡我打印出了1~50時的結果,可以看出得到的結果是1~9的迴圈。
num: 1, result: 1
num: 2, result: 2
num: 3, result: 3
num: 4, result: 4
num: 5, result: 5
num: 6, result: 6
num: 7, result: 7
num: 8, result: 8
num: 9, result: 9
num: 10, result: 1
num: 11, result: 2
num: 12, result: 3
num: 13, result: 4
num: 14, result: 5
num: 15, result: 6
num: 16, result: 7
num: 17, result: 8
num: 18, result: 9
num: 19, result: 1
num: 20, result: 2
num: 21, result: 3
num: 22, result: 4
num: 23, result: 5
num: 24, result: 6
num: 25, result: 7
num: 26, result: 8
num: 27, result: 9
num: 28, result: 1
num: 29, result: 2
num: 30, result: 3
num: 31, result: 4
num: 32, result: 5
num: 33, result: 6
num: 34, result: 7
num: 35, result: 8
num: 36, result: 9
num: 37, result: 1
num: 38, result: 2
num: 39, result: 3
num: 40, result: 4
num: 41, result: 5
num: 42, result: 6
num: 43, result: 7
num: 44, result: 8
num: 45, result: 9
num: 46, result: 1
num: 47, result: 2
num: 48, result: 3
num: 49, result: 4
num: 50, result: 5
依據上述規律我們可以寫出簡單的程式碼:
class Solution {
public:
int addDigits(int num) {
if(!num) return 0;
int a = num % 9;
if (a) return a;
else return 9;
}
};