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?
Hint:
https://en.wikipedia.org/wiki/Digital_root
从维基百科中得出结论:(num-i)%9 == 0 满足此条件的i就是num的数字根(digital root)
我们可以举几个例子简单验证一下:
首先无论是多少位的数,都会变成两位数或者一位数的形式,且最终一定会变成一位数的形式:
10=9+1, 11=9+2, 12=9+3, 13=9+4, 14=9+5, 15=9+6, 16=9+7, 17=9+8, 18=9+9, 19=9+9+1=2*9+1, ……, num=k*9+i
所以,思路就变得非常简单:
①如果输入的数字小于10,则直接返回,这个数本身就是自己的树根
②如果输入的数字大于等于10:若它能不能被9整除,则返回其除以9的余数;否则返回9
程序如下:
class Solution {
public:
int addDigits(int num) {
if (num < 10) {
return num;
}
return (num%9!=0 ? num%9 : 9);
}
};