题目链接:https://leetcode.com/problems/add-digits/
题目: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.
解题思路:思路比较简单,就是求每个位的数之和,判断是否为小于10的数,是就返回结果,不是就继续做求每位数之和的操作。
示例代码:
public class Solution
{
public int addDigits(int num)
{
int temp=addSum(num);
if(temp<10)
{
return temp;
}
else
return addDigits(temp);
}
/**
* 求每位的数之和
* @param num
* @return
*/
private int addSum(int num)
{
if(num<10)
return num;
int i=0;
int sum=0;
while(num!=0)
{
i=num%10;
sum+=i;
num=num/10;
}
return sum;
}
}