Leetcode-整数反转

2.整数反转

题目内容:

Leetcode-整数反转

思路与代码:

首先要考虑的是溢出的问题,因为中间很容易出现res*10就溢出了,所以在下一步进行之前首先要判断res*10会不会超出Max值。

class Solution {
public:
    int reverse(int x) { 
        //判断是否溢出,2^31=2147483648
        #define Max 2147483647
        #define Min (-Max-1) 
        //去除符号位
        int flag=1;
        int res=0;
        if(x<0)
        {
            flag=-1;
            if(x>Min)
                x=-x;
            else return 0;
        }
        while(x>0)
        {
            if(res!=0&&Max/abs(res)<10 ||((unsigned int)abs(res*10)+(unsigned int)(x%10))>Max) 
                return 0;
            res=res*10+flag*(x%10); 
            x=x/10;
                
        } 
            return res;
    }
};