LeetCode 258. Add Digits

来源:互联网 发布:期货行情软件下载 编辑:程序博客网 时间:2024/05/21 21:14

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