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;
}
}