LeetCode试题详解

7. 反转整数

2018-10-27  本文已影响4人  Gunther17

给定一个 32 位有符号整数,将整数中的数字进行反转。

示例 1:
输入: 123
输出: 321

示例 2:
输入: -123
输出: -321

示例 3:
输入: 120
输出: 21

假设我们的环境只能存储 32 位有符号整数,根据这个假设,如果反转后的整数溢出,则返回 0。

通过code c++:

class Solution {
public:
    int reverse(int x) {
        int mabeflow = 0;
        while (x != 0){
            int nooverflow = mabeflow;
            mabeflow = nooverflow * 10 + x % 10;
            
            /*不行int newres = mabeflow*10;if ((mabeflow - newres)  != x % 10)
            因为在mabeflow和newres同时溢出时还是相差x % 10
            然而在下面的正确判断中nooverflow还没溢出,乘以10以后mabeflow就溢出
            */

            //如果溢出,让编译器去检测案例1534236469应该返回0
            if ((mabeflow - x % 10) / 10 != nooverflow)
                return 0;
            x /= 10;

        }

         
        return mabeflow;
    }
};

自己错误代码分析:

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0){
            int newres = res * 10;
            res = res*10+x % 10;
            //如果溢出,让编译器去检测案例1534236469应该返回0
            if ((res - newres) != (x % 10))
                return 0;
            x /= 10;

        } 
        return res;
    }
};

注意:如果溢出,让编译器去检测案例1534236469应该返回0

参考

上一篇 下一篇

猜你喜欢

热点阅读