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
. Since2
has only one digit, return it.
Follow up:
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 Wikipedia article useful.
這道題讓我們求數根,所謂樹根,就是將大於10的數的各個位上的數字相加,若結果還大於0的話,則繼續相加,直到數字小於10為止。那么根據這個性質,我們可以寫出一個解法如下:
解法一:
class Solution { public: int addDigits(int num) { while (num / 10 > 0) { int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } num = sum; } return num; } };
但是這個解法在出題人看來又trivial又naive,需要想點高逼格的解法,一行搞定碉堡了,那么我們先來觀察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的數對9取余就是0了,為了得到其本身,而且同樣也要對大於9的數適用,我們就用(n-1)%9+1這個表達式來包括所有的情況。還有個特殊情況需要考慮一下,當num為0的時候,那么就會出現 -1 % 9 的情況,這個其實挺煩人的,因為C++和Java會給出商0余-1的結果,而Python會給出商-1余8的結果,博主搜了一下,好像是說當有一個負數存在的時候,C++/Java會盡可能讓商大一些,而Python會讓商小一些,所以結果不統一就神煩,那么只好做個額外判斷了,特殊處理一下0的情況就OK了,所以解法如下:
解法二:
class Solution { public: int addDigits(int num) { return (num == 0) ? 0 : (num - 1) % 9 + 1; } };
類似題目:
參考資料:
https://leetcode.com/problems/add-digits/