题目如下:
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?
这道题我的答案:
int addDigits(int num)
{
if(num < 10)
return num;
else
return addDigits(num % 10 + num / 10);
}
貌似我虽然没用循环,但是用了递归。。查了一下别人的解答:
int addDigits(int num) {
int a = (num-1)%9+1;
return a;
另附
https://en.wikipedia.org/wiki/Digital_root
好像也有人说,这不就是模9的余数嘛,如果是9的倍数,就是9。余数就是这个