I was trying to solve this problem on LeetCode where you have to reverse an integer using a function. The constraint is that if the reversed number goes outside the signed 32-bit integer range, i.e. (-2^31) to (2^31 - 1) then you return 0. When I use an integer for the reversed variable like this
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return rev;
}
}
IntelliJ IDEA shows that the
Condition 'rev > Integer.MAX_VALUE' is always 'false'
However, when I use a long instead of int, the problem is resolved and the program works as you would expect.
class Solution {
public int reverse(int x) {
long rev = 0;
while (x != 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if((rev > Integer.MAX_VALUE) || (rev < Integer.MIN_VALUE))
return 0;
return (int)rev;
}
}
I was wondering why is that the case?