题目:
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?
思路:
乍一看确实没有思路,但是后来在看了discuss之后明白了这又是一个找规律的问题。
代码如下:
public class Solution {
public int addDigits(int num) {
if(num == 0){
return 0;
}
int mynum = num % 9;
if(mynum == 0){
mynum = 9;
}
return mynum;
}
}
需要注意的是需要将模数得到的0值改成9.