LeetCode 258. 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.


Follow up:
Could you do it without any loop/recursion in O(1) runtime?


这个题一看例子我就想又要递归又要迭代的,但是看这底下说的好像不用递归和迭代还能在O(1)时间内完成,这肯定又是跟数字本身有关,试了试与并或非都不行,忽然想起取余,发现对9取余好像不错,急急忙忙就提交了,结果很显然这种靠猜的确实没想严谨,又经过了错误提示就把程序改成这样了

class Solution {
public:
    int addDigits(int num) {
        int result = 0;
        if(num < 10){
            return num;
        }else{
            result = num % 9;
            return (result == 0 ? 9 : result);
        }
    }
};

百度了下发现有人说有个这种公式

d(n) = num%9 == 0 ? (num==0? 0 : 9) : num%9


d(n) = 1 + (n-1) % 9

说实话我这数学功底有限确实不太知道怎么推到的。

另外再转贴上两个迭代和递归的吧

class Solution {
public:
    int addDigits(int num) {
        while(num/10>0){
            int sum = 0;
            while(num!=0){
                sum += num%10;
                num = num/10;
            }
            num = sum;
        }
        return num;
    }
};



/**
 * 功能说明:LeetCode 258 - Add Digits
 * 开发人员:Tsybius2014
 * 开发时间:2015年8月26日
 */
public class Solution {
     
    /**
     * 给定整数不断将它的各位相加,直到相加的结果小于10,返回结果
     * @param num
     * @return
     */
    public int addDigits(int num) {
        int next = getNext(num);
        while (next >= 10) {
            next = getNext(next);
        }
        return next;
    }
     
    /**
     * 获取整数各位相加后的和
     * @param num
     * @return
     */
    private int getNext(int num) {
        String s = String.valueOf(num);
        int sum = 0;
        for (char ch : s.toCharArray()) {
            sum += (ch - '0');
        }
        return sum;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值