Simple way to deal with overflow


  • 0
    M

    however, I don't think my solution is right to all cases.
    e.g. x....y , if y...x >INTMAX, then the actual reversed int maybe a...x, then my solution is wrong.
    my question is : does this case exist ?

    class Solution {
    public:
        int reverse(int x) {
            int res(0),digit(0);
            bool sign(false);
            
            if(x<0){
                sign=true;
                x=abs(x);
            }
            
            while(x){
                res*=10;
                digit = x%10;
                x = x/10;
                res+=digit;
            }
            
            if(res%10!=digit) return 0;// the last digit should equal to the first digit of the origianl number
            if(sign) return -res;
            return res;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.