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) {
int result =10;
if(num/10 == 0)
return num;
while(result/10 !=0){
//num = result;
result = 0;
while(num/10 != 0){
result = result + num%10;
num /= 10;
}
result += num;
if(result/10 !=0)
num = result;
}
return result;
}
};
在考虑的情况下,找到其规律:(num-1) % 9 + 1,直接找需要一些数论的知识见:http://my.oschina.net/Tsybius2014/blog/497645
即
public class Solution {
public int addDigits(int num) {
return (num-1) % 9 + 1;
}
}