Leetcode -- 258 数位相加

258.

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 = 111 + 1 = 2. Since 2 has only one digit, return it.

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

思路一:常规思路: 不断取出数字的每一位,求得和,然后将和 递归计算。

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

思路二:

一个数,假如设为ABCD,则实际上这个数可以表达为num = A*1000+B*100+C*10+D。

可分解为num = (A+B+C+D) + (999*A+99*B+9*C),因为我们需要求的是A+B+C+D,所以我们可以采用%的方法。

因为(999*A+99*B+9*C)肯定是9的倍数,则 num % 9 = A+B+C+D,如果A+B+C+D>=10,对9取余,可依照刚才的方法继续分析,结果是一样的。

但是,当num = 9时,9 % 9 = 0,不符合题目的要求,所以算法的核心是     result = (num - 1)% 9 + 1

class Solution {
public:
    int addDigits(int num) {
         return (num - 1) % 9 + 1;
    }
};
原文地址:https://www.cnblogs.com/simplepaul/p/7143221.html