Reverse Integer

This way is inexact in handling the overflow , some integer may be judged as illegal mistakenly .
class Solution {
public:
    int reverse(int x) {
           int result = 0;

    while (x != 0){
        // judge the int overflow
        if (result > INT_MAX/10 || result < INT_MIN/10)
            return 0;
        result = result * 10 + x % 10;
        x /= 10;
    }
    return result;
    }
};

A better way :


class Solution {
public:
    int reverse(int x) {

        int res = 0;
        int sign = 1;
        int MAX = INT_MAX;

        if(x < 0)
        {
            sign = -1;
            MAX = INT_MIN;
        }
        while(x != 0)
        {
            // handle the overflow exactly
            if(((MAX - x%10)/10)*sign >=  res*sign)
                res = res*10 +x%10;
            else
                return 0;
            x = x/10;
        }
        return res;
    }
};

tips:

  • how to judge the int overflow ?
    • INT_MAX : 2147483647
    • INT_MIN : -2147483648
    • Both the number have 10 places , and when the result more than first 9 places(214748364,-214748364) ,then we think it is illegal , you can not compare a number with the INT_MAX or INT_MIN, cause the number itself already was illegal.
    • when a number in
  • The normal mind is that MAX >= (res*10 + x%10)(assuming the integer is positive),but there may be a overflow in right side , so we transform it to (MAX - x%10)/10 >= res , anyway there will not be a overflow in left side .