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.
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.
基本思路:
Digital root,維基百科詳細的介紹這個問題:https://en.wikipedia.org/wiki/Digital_root
10進制下的 解法公式爲:
- dr(n) = 0 if n == 0
- dr(n) = 9 if n != 0 and n % 9 == 0
- dr(n) = n mod 9 if n % 9 != 0
or
- dr(n) = 1 + (n - 1) % 9
即數爲0時,結果爲0;被9整除時,結果爲9;其他則爲對9的餘數。
基本上就是爲9的餘數,再加上兩個特例。
可以從下面的規律,比較直觀的理解和推導這個公式。
~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 ....
當輸入的整數遞增時,輸出的dr是週期性的。
簡單的證明一下這個週期性:
digit root基本運算爲:個位數 和 其他位上的數相加。
當兩個輸入的數個位數相差1時,其digit root的運算結果也只會相差1.
class Solution {
public:
int addDigits(int num) {
return 1 + (num-1) % 9;
}
};