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;
}
}
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.
Integer.MAX_VALUE
is 2147483647
That means: Integer.MAX_VALUE/10
is 214748364
And you're about to do: rev = rev * 10 + pop
So if rev > 214748364
, then rev * 10
will cause overflow.
Or if rev == 214748364
, then rev * 10
is 2147483640
, and rev * 10 + pop
will cause overflow if pop > 7
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.