Search code examples
javastringstringbuilder

Reverse a number using String builder in java


Problem Statement: Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123 Output: 321 Example 2:

Input: -123 Output: -321

My Solution:

class Solution7{
public int reverse(int x) {
    if(x>Integer.MAX_VALUE || x<Integer.MIN_VALUE) {
        return 0;
    }


    StringBuilder S_rev = new StringBuilder();
    String S_r_v=S_rev.append(Math.abs(x)).reverse().toString();//.toString() String builder to String

   double reverse_no=Double.parseDouble(S_r_v);

    if (x < 0) {
        return -(int)reverse_no;
    }
    return (int)reverse_no;

}

}

My Solution is ok for most of the test case. But it cannot pass one test case and I got a error

Error: Line 10: java.lang.NumberFormatException: For input string: "8463847412-"

If someone know what type of error it is please discuss.

Thank you in advance.


Solution

  • It seems like you are trying to pass in Integer.MIN_VALUE

    When you pass in the minimum integer value, Math.abs seems to return a negative number as stated here

    https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#abs-int-

     Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.
    

    You can either check for x<=Integer.MIN_VALUE and return 0 if x is Integer.MIN_VALUE or handle the special case for Integer.MIN_VALUE

     if(x== Integer.MIN_VALUE)
          return -8463847412;