-4
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt()
    String s=new StringBuilder().append(n).reverse().toString();

    System.out.println(Integer.parseInt(s));

I am trying to reverse a number but when I try to give negative numbers for example if I give input as -124 it gives me NumberFormatException. Can anyone tell me why this is happening?

1 Answers1

0

Reverse of -X is X- hence the - at the end of string is causing the NumberFormatException.
Here is a simple ways to handle both positive & non-positive numbers:

    public static void main (String [] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        // Make `n` positive if `n` is negative
        String s = new StringBuilder().append(n<0 ? -n : n).reverse().toString();
        // Print the reverse string along with `-` sign if n<0
        System.out.println((n<0 ? "-" : "") + Integer.parseInt(s));
    }
GURU Shreyansh
  • 881
  • 1
  • 7
  • 19