Rohith L. Rohith L. - 4 months ago 8
Java Question

inputing negative numbers into a number reversal program

My program is supposed to take in random integers and reverse them. It currently works for all positive integers that are no more than ten digits long.

import java.util.Scanner;

public class Program2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int input;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
input = scanner.nextInt();
System.out.print("Its reversal is ");
reverse(input);
System.out.println();;
}
public static void reverse(int number) {
if(number < 10 && number > 0) {
System.out.println(number);
return;
}
else {
System.out.print(number % 10);
reverse(number/10);
}
}
}


I've been having trouble finding a way for the program to return the reversals of negative numbers. What's the simplest way to do that?

Answer

Per the comments above, it looks like you want the reverse of -123 to be -321. If so, I think this code should work:

public static void reverse(int number) {
    if (number < 0) {
        System.out.print("-");
        reverse(number * -1);
    } else if (number < 10) {
        System.out.println(number);
    } else {
        System.out.print(number % 10);
        reverse(number / 10);
    }
}

(I dropped the && number > 0 because you had an infinite loop if the input is exactly 0.)


Note: this code will give a StackOverflowError for number == Integer.MIN_VALUE, since -Integer.MIN_VALUE == Integer.MIN_VALUE. You can fix this as follows:

if (number < 0) {
  System.out.print("-");
  if (number == Integer.MIN_VALUE) {
    System.out.print(-(number % 10));
    number /= 10;
  }
  reverse(-number);
} else if ...
Comments