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.

思路

一开始没有思路的时候,可以先自己写两个例子来观察是否有规律可以寻找:

Example 1: Given num = 285, the process is : 2 + 8 +5 = 15, 1 + 5 = 6
Example 2: Given num = 6942, the process is : 6 + 1 + 4 + 7 = 28, 2 + 8 = 10, 1 + 0 = 1

通过观察上面的三个例子,我们可以很容易的想出一种解决方法:通过将这个数字的每一位进行相加,如果加出来的数字不是一位数,那么继续相加,直到最后那个数只有一位。这种思路可以使用recursion 或者 iteration的方法来实现。

// 通过循环的方式来实现
public int addDigits(int num) {
    int tmp = 0;
    while (num > 0) {
        tmp += num % 10;
        if (tmp >= 10) {
            tmp = tmp % 10 + tmp / 10;
        }
        num = num / 10;
    }
    return tmp;
}
// 通过迭代的方式实现
public int sumDigits(int n){
    if(n==0)
        return 0;
    return (n%10) + sumDigits(n/10);
}
public int addDisits(int num) {
    while(num/10>0){ 
        num = sumDigits(num); 
    } 
    return num;
}

循环和迭代的方式思想都差不多的,都是通过一位一位的相加,得出来最后的那个数字。

但是,我们再仔细观察一下,依然发现其中会有一定的规律的。我们多举几个例子

Example 3: Given num =10, the process is : 1 + 0 = 1
Example 4: Given num =11, the process is : 1 + 1 = 2
Example 5: Given num =12, the process is : 1 + 2 = 3
Example 6: Given num =18, the process is : 1 + 8 = 9

这样就可以很清晰的看出,any number that is divisible by 9,the sum of the digits in the number is also divisible by 9.任何一个可以被9整除的数,它们的每一位的数字相加的和也能被9整除。
所以,我们通过判断这个数是否能够被9整除,就知道这个数的每一位相加的最终结果是否为9。如果不能被9整除,那么余数正好就是每一位相加的结果。

public int addDigits(int num) {
if(num<10)
    return num;
else if(num%9 ==0)
    return 9;
else
    return num%9;        
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值