Accepted but not satisfied with the if-statements checking for overflow


  • 2
    K

    I wish the two if-statements in the solution below can be simplified in any way possible.

    class Solution {
    public:
        int reverse(int x) {
            int result = 0;
            while (x != 0)
            {
                int a = x % 10;
                if (a > 0 && (result > INT_MAX/10 || (result == INT_MAX/10 && a > 7))) return 0;
                if (a < 0 && (result < INT_MIN/10 || (result == INT_MIN/10 && a < -8))) return 0;
    
                result = result*10 + a;
                x /= 10;
            }
            return result;
        }
    };

  • 6
    Z

    If you declared result as a long, you could check for overflow directly after updating result.


  • 0
    K

    Man, why didn't I think of that?
    declaring as "long long" does it.

    long long result = 0;
    
    if (result > INT_MAX || result < INT_MIN) return 0;
    

    Thanks.


  • 0
    E

    Why did you need to to declare as long long?


Log in to reply
 

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