[leetcode]--258. Add Digits

Question 258:

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

中文解释: 对于一个非负的整数n, 把其每位数的数字相加求和,直到其和小于10.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

算法这里提供两种思路:

1)不断遍历求和直到小于10

这是一种比较直观的想法,只需要不断的求和就行了,下面给出代码:

/**
 * 这个是最普通的算法,不停循环求出每位的和.
 * @By 娄宇庭
 * @param num
 * @return
 */
public static int addDigits(int num) {
    if(num<10)
        return num;
    int result = num;

    while (result>=10){
        int temp = 0;
        //将待求的多位数先转换成字符串再转换成字符数组;
        char[] numStrs = new Integer(result).toString().toCharArray();
        //遍历字符数组,获取每个字符数组代表的数,然后相加
        for(int i=0; i<numStrs.length; i++){
            temp += Integer.valueOf(String.valueOf(numStrs[i]));
        }
        result = temp;
    }
    return result;
}

2)利用取余的特性求解:

example: 比如438
438 == 40*10 + 3*10 +8
4+3+8 == 4*(10%9)(10%9) + 3(10%9) + 8%9=15

再比如15:
15 == 1*10 +5
1+5 == 1*(10%9)+5%9 =6

得出规律: ab%9%9%9 == ab%9;

参考思路:
https://discuss.leetcode.com/topic/21588/1-line-java-solution

下面给出实现代码:

public static int addDigits_reference(int num) {
    return num==0?0:(num%9==0?9: num%9);
}

3. 测试:

//测试用例
public static void main(String[] args) {
    LogUtil.log_debug(""+addDigits_reference(38));
}

运行结果:

2017-02-03 23:49:06:2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值