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?
s思路:
1. 如何下手?不用loop.也就是说不能一位一位的取,不用考虑细节的来做,方法就两种,不是bottom-up,就是top-down.
2. 这就是说用一个top-down的系统方法,一般数学的方法就比较好:参考了https://en.wikipedia.org/wiki/Digital_root
3. 就是n%9的余数,如果余数等于0,就返回9.所以修正一下就是:(n-1)%9+1
4. 应该能猜测到,最后结果是0-9,所以才都可以猜一下用余数
class Solution {
public:
int addDigits(int num) {
if(num<1) return num;
return (num-1)%9+1;
}
};