Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse Integer leetcode: Why does overflow occur only if 7 or greater is added to INT_MAX?

Tags:

java

I have the solution provided by Leetcode and the part that confuses me is the fact that adding 7 (or a lower value) to Integer.MAX_VALUE or adding -8 (or a lower value) to Integer.MIN_VALUE does not result in overflow or underflow respectively.

My logic is that if you have Integer.MAX_VALUE, adding 1 will cause overflow. And if you have Integer.MIN_VALUE, subtracting 1 will cause underflow. Where is my understanding of overflow and underflow wrong?

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev ==     Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}
like image 922
Shisui Avatar asked Dec 11 '22 03:12

Shisui


1 Answers

Yes, normally adding 1 to Integer.MAX_VALUE will result in overflow, as will subtracting 1 from Integer.MIN_VALUE. But that is not what is happening here.

This code is performing integer division by 10, which truncates any decimal portion. When dividing Integer.MAX_VALUE (2147483647) by 10, the code anticipates multiplying by 10 and adding the next digit. That quotient is 214748364, and multiplying by 10 is 2147483640, with the possibility of adding another 7 without overflowing. Similarly on the negative side, dividing Integer.MAX_VALUE (-2147483648) by 10 yields -214748364, multiplying by 10 yields -2147483640, with the possibility of adding another -8 without overflowing.

This code takes into account the last digit of the extremes of the range of Integer values and carefully avoids overflow.

like image 165
rgettman Avatar answered May 23 '23 09:05

rgettman