0

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?

reek1729
  • 9
  • 1
  • 1
    Because when `rev` is an `int` it literally cannot be greater than `Integer.MAX_VALUE`. The other condition is also impossible. Because it is an `int`. That's like asking for one value greater than the greatest possible value. Or one value less than the least possible value. With a `long` it is possible to have a value greater than the greatest possible `int` value. Or less than the least possible `int` value. `long` is 64-bits. – Elliott Frisch May 14 '22 at 05:45

2 Answers2

0

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.

TheFungusAmongUs
  • 1,423
  • 3
  • 11
  • 28
0

For me this works...

class Solution {
    public int reverse(int x) {
        int mod = 0, rev = 0;
            while(x!=0){
                if(rev < Integer.MIN_VALUE/10 || rev > Integer.MAX_VALUE/10){
                return 0;
                }
            mod = x%10;
            x = x/10;
            rev = rev*10 + mod;
            }
            return rev;
    }
}
Krushna Chulet
  • 1,625
  • 1
  • 10
  • 9