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.
Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
思路一:对num各位相加,如果相加结果大于10则重复操作,
class Solution {
public int addDigits(int num) {
int temp = num;
while( temp >= 10){
temp = 0;
while( num != 0){
temp += num % 10;
num /= 10;
}
num = temp;
}
return temp;
}
}
思路二:此题存在规律,num对9取余,如果不为0则即是结果。
class Solution {
public:
int addDigits(int num) {
if( num < 10)
return num;
int result = num % 9;
if( result == 0)
return 9;
else
return result;
}
};