题目要求:
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?
数学上来说,就是求这个数的数字根
用数学公式来解决,结果如下:
public class Solution {
public int addDigits(int num) {
return (num-1)%9+1;
}
}
用循环来做,更方便理解:
public int addDigits(int num) {
while(num>=10)
{
int temp=num;
int sum=0;
while(temp>0)
{
sum+=temp%10;
temp = temp/10;
}
num = sum;
}
return num;
}