您的位置:首页 > 其它

【LeetCode OJ 258】Add Digits

2016-01-15 20:18 302 查看
题目链接: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;
	}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: