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?
题目大意:给出一个非负整数num,重复相加它的每一位直到最后只剩1位。
解题思路1:利用递归解决问题。
代码如下:
int addDigits(int num) {
return num/10 ? addDigits(num%10+addDigits(num/10)) : num;
}
解题思路2:利用公式dr(n) = 1 + ((n - 1) mod 9)可以在O(1)时间内求解,详解见digital root
代码如下:
int addDigits(int num) {
return 1 + (num-1)%9;
}