Search code examples
javastringnumberformatexception

Number Format Exception for specifically -2147483648


I have written a method to reverse a signed int. If the reversed number is not in range of INT_MAX and INT_MIN it will return 0. It is working for almost all cases except for -2147483648 While debugging i have found that the code is not handling sign properly for -2147483648 while its working for different signed inputs.

Can someone explanin why Math.abs(x) is not working properly for this testcase. Method is given below.

public int reverse(int x) {
        boolean flag = (x>0);
        x = Math.abs(x);

        String num = new StringBuilder(Integer.toString(x)).reverse().toString();
        
        long temp = Long.parseLong(num);

        if(!flag){
            temp = -temp;
        }

        if((Integer.MAX_VALUE < temp) || ( temp < Integer.MIN_VALUE)){
            return 0;
        }

        return (int) temp;
    }

Solution

  • In Java, the integer representation goes from Integer.MIN_VALUE = -2^31 = -2147483648 to Integer.MAX_VALUE = 2^31-1 = 2147483647.

    There is no positive value opposite to -2147483648 that can be properly represented in Java's integer range when performing Math.abs(x). Hence, when the parameter -2147483648 is passed to the method, the result overflows back to the smallest representable integer, which is -2147483648 again, since Math.abs() simply negates the given parameter when this is negative. Therefore, in your line

    String num = new StringBuilder(Integer.toString(x)).reverse().toString();
    

    you're actually reversing -2147483648 into 8463847412-, which causes the NumberFormatException being thrown when performing

    long temp = Long.parseLong(num);
    

    since 8463847412- is not a long.