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?
class Solution {
public:
int addDigits(int num) {
return (num-1)%9+1;
}
};
設數字爲四位數,各個位分別是abcd,其他情況類似。
則
abcd=a*1000+b*100+c*10+d
=a+b+c+d+(a*999+b*99+c*9)
=a+b+c+d+(a*111+b*11+c)*9
設n=a+b+c+d
n同樣可以做如上展開,反覆迭代,直到前面數字之和爲個位數,形如n+m*9並且此時這個個位數的取得滿足題目的要求的返回值,此時後面的數字爲9的倍數。要求的這個個位數只需對九求模即可(因爲這個數可能是9,所以要先減一最後加一)。