题目
Given a non-negative integer num
, repeatedly add all its digits until the result has only one digit.
Example:
Input:38
Output: 2 Explanation: The process is like:3 + 8 = 11
,1 + 1 = 2
. Since2
has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
十分钟尝试
利用递归调用,除以10,对10求mod获取每位数字,逻辑不是问题,已经一遍ok,代码如下,但是题目的followup需要研究一下,先上一个递归版本:
class Solution {
public int addDigits(int num) {
int res=caculate(num);
if(res/10==0){
return res;
}
return addDigits(res);
}
private int caculate(int num){
int res=0;
while(num>0){
res+=num%10;
num=num/10;
}
return res;
}
}
非递归非循环解法
class Solution {
public int addDigits(int num) {
return 1 + (num - 1) % 9;
}
}