【leetcode】【c++】258. add digits

版权声明:来自 T2777 ,请访问 https://blog.csdn.net/T2777 一起交流进步吧 https://blog.csdn.net/T2777/article/details/87879705

题目介绍:

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

Example:

Input: 38
Output: 2 
Explanation: 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?

题目要求给定一个整数,将它的各位进行相加,如果和为一个个位数,那么输出,否则继续进行各位的相加。

首先注意到 如果给定一个特别大的数接近于 maxint , 请款将会变得非常的复杂,无论是用数组进行存储都会出现很多的问题,然而实际这种请款是不会出现的,因为要想得到一个个位数,最后相加的结果只能是一个个位数,即不超过10,说明给的数应当比较的小。

方法一:

按照递归 + 循环的方法进行解决:

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

方法很容易理解,不做详细描述,递归是可以调用自己的。

方法二:

只用到循环:

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

以上 2 种方法的效率基本相同。

方法三:

尝试使用数学技巧进行问题的求解,代码为:

class Solution {
public:
    int addDigits(int num) {
        if(num < 10)
            return num;
        return ((num -1) % 9 + 1);
    }
};

 代码解释:

例如一个2位数 ab = a * 10 + b,  则 ab % 9 = (a * 9 + a + b)% 9 = (a + b) % 9 ;

3位数 abc = a * 100 + b * 10 + c ,则 abc % 9 = (a * 99 + b * 9 + a+ b + c) % 9 = (a + b + c) % 9;

用上面的规律,38 % 9 = 11% 9 = 2 % 9 = 2; 这与题目要求的方法完全一致,为了当 num = 9 时,返回的结果是 9 而不是 0,可以用(num - 1 ) % 9 + 1 去解决, ( 9 - 1 ) % 9 + 1 = 9 ,完全一致,问题得到解决。

猜你喜欢

转载自blog.csdn.net/T2777/article/details/87879705
今日推荐