原题链接 https://leetcode.com/problems/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.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
abc = a*100 + b * 10 + c;
a + b + c = abc - 99*a - 9*b = abc - (11 * a + b)* 9 = r;
假设r是一位数 则 abc = k * 9 + r, k = 11 *a + b;
也就是说r = abc % 9; 当然这并不是完全试用于所有条件, 当abc能够被9整除的时候,r = 9 而不是 0;
真正适用于所有条件的是 abc - k * 9, 直到差值 < 10;
所以只需要加上一个判断就行了,如果abc!=0&& abc % 9 == 0 直接返回 9
class Solution {
public:
int addDigits(int num) {
if(num != 0 && num % 9 == 0)return 9;
return num % 9;
}
};