'LeetCode 7: Reverse Integer | why does it work with a long but not with an int?

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?



Solution 1:[1]

In the first code block, rev is an integer. Thus, it is impossible for it to be greater than Integer.MAX_VALUE - the maximum value for an integer.

With a long, it is possible to have a value greater than the greatest possible int value. A Java int is a signed 32-bit value. A Java long is a signed 64-bit value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1