Reverse Number Program in Java: Methods and Techniques

In today’s blog we will understand what is reverse number in Java? What are the different methods to reverse a number in java? Also we will learn the pros and cons of different methods of reverse a number in Java with best use cases.

What is the Reverse a Number in Java?

Reverse a number in Java means changing its order of digits. For example, reversing the number 123 gives us 321. This is a common task in programming, and Java provides several ways to accomplish it. In this blog, we will explore some of these methods and how to implement them.

Four Methods of write reverse a number in java

There are four different methods to reverse a number in Java: using while loop, using for loop, using recursion, and using string. Each method has its advantages and disadvantages, and we will explore them in detail with the help of code examples and explanations.

Method 1: Reverse a Number in Java Using while loop:

Check out the code given below to better understanding how to reverse a number in java using while loop:

import java.util.Scanner;

public class ReverseNumberWhileLoop {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int number = scanner.nextInt();
      int reversedNumber = 0;
      while (number != 0) {
         int digit = number % 10;
         reversedNumber = reversedNumber * 10 + digit;
         number /= 10;
      }
      System.out.println("Reversed Number: " + reversedNumber);
   }
}

Explanation of the code:

This code takes an input number from the user and initializes a reversedNumber variable to 0. It then enters a while loop that runs as long as the number is not equal to 0. In each iteration of the loop, the code extracts the last digit of the number using the modulo operator (%), multiplies the reversedNumber variable by 10 and adds the extracted digit to it. The number is then divided by 10 to remove the last digit. The final result is the reversed number.

Learn How to Generate Random Numbers in Javascript, Now!

Output:

Enter a number: 12345
Reversed Number: 54321

Method 2: Reverse a Number in Java Using for loop:

Check out the code given below to better understanding how to reverse a number in java using for loop:

import java.util.Scanner;

public class ReverseNumberForLoop {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int number = scanner.nextInt();
      String numberString = Integer.toString(number);
      String reversedNumberString = "";
      for (int i = numberString.length() - 1; i >= 0; i--) {
         reversedNumberString += numberString.charAt(i);
      }
      int reversedNumber = Integer.parseInt(reversedNumberString);
      System.out.println("Reversed Number: " + reversedNumber);
   }
}

Explanation of the code:

This code takes an input number from the user and converts it to a string using the Integer.toString() method. It then initializes a reversedNumberString variable to an empty string and enters a for loop that runs from the last character of the string to the first character. In each iteration of the loop, the code adds the current character to the reversedNumberString variable. Finally, it converts the reversedNumberString back to an integer using the Integer.parseInt() method. The final result is the reversed number.

Output:

Enter a number: 4589
Reversed Number: 9854

Method 3: Reverse a Number in Java Using Recursion:

Take a look at this Java code that illustrates how to reverse a number using a for loop

import java.util.Scanner;

public class ReverseNumber {
    public static int reverse(int num) {
    if (num < 10) {
        return num;
    } else {
        int lastDigit = num % 10;
        int remainingDigits = num / 10;
        return (int) ((lastDigit * Math.pow(10, Integer.toString(remainingDigits).length())) + reverse(remainingDigits));
    }
}

public static void main(String[] args) {
    int num = 12345;
    int reversed = reverse(num);
    System.out.println("Original number: " + num + "\n");
    System.out.println("Reversed number: " + reversed);
}
}

Explanation of the code:

This code uses a recursive method to reverse a number. The reverse method takes an integer argument and returns the reversed number as an integer.

The base case of the recursion is when the input number is less than 10, in which case the method simply returns the input number.

For numbers greater than 10, the last digit of the number is extracted using the modulo operator, and the remaining digits are obtained by dividing the input number by 10. The Math.pow method is used to determine the place value of the last digit in the reversed number. The method then recursively calls itself with the remaining digits, and concatenates the reversed last digit to the result.

The main method calls the reverse method with an input number of 12345, and prints both the original number and the reversed number to the console.

Check out our blog on Create Objects in Java here!

Output:

Original number: 12345
Reversed number: 54321

Method 4: Reverse a Number in Java Using String:

Here’s an example Java code that uses a for String to reverse a number.

import java.util.Scanner;

public class ReverseString {
public static int reverse(int num) {
    String numStr = Integer.toString(num);
    StringBuilder reversedStr = new StringBuilder(numStr).reverse();
    return Integer.parseInt(reversedStr.toString());
}

public static void main(String[] args) {
    int num = 4586;
    int reversed = reverse(num);
    System.out.println("Original number: " + num);
    System.out.println("Reversed number: " + reversed);
}

}

Explanation of the code:

This code uses the StringBuilder class to reverse a number by converting it to a String. The reverse method takes an integer argument and returns the reversed number as an integer.

The Integer.toString method is used to convert the input number to a String. The StringBuilder class is then used to reverse the order of the characters in the String. The toString method of the StringBuilder class is called to obtain the reversed String, and the Integer.parseInt method is used to convert the String back to an integer.

The main method calls the reverse method with an input number of 12345, and prints both the original number and the reversed number to the console.

Output:

Original number: 4586
Reversed number: 6854

Comparison of the Different Methods

Java offers multiple methods to reverse a number, each with its own advantages and disadvantages. This section will compare these methods and provide insights into their best use cases.

Know How to Print ASCII Value in Java, Here!

Advantages and Disadvantages of different methods to reverse number in Java

Using While Loop: One of the advantages of using a while loop is that it’s easy to implement and understand. It’s also useful for reversing numbers of any length. However, it can be slower than other methods, especially when dealing with large numbers.

Using For Loop: A for loop is another easy-to-implement method that is efficient for small to medium-sized numbers. It’s also helpful in situations where you need to iterate over a fixed number of elements. However, it can be slower than other methods for larger numbers.

Using Recursion: Recursion is a powerful technique for reversing numbers, as it allows for a clean and concise implementation. It’s also efficient for small to medium-sized numbers. However, it can be slower than other methods for larger numbers, and it can be harder to understand for beginners.

Using String: Converting the number to a string and then reversing it is a straightforward and easy-to-understand method. It’s also efficient for small to medium-sized numbers. However, it can be slower than other methods for larger numbers, and it may not be suitable for some use cases where the number needs to remain a number.

Best Use Cases of Reverse a number in Java

Using While Loop: The while loop method is ideal for situations where you need to reverse numbers of any length and when speed is not a critical factor. It’s also useful for beginners who are just starting to learn Java.

Using For Loop: The for loop method is ideal for situations where you need to reverse small to medium-sized numbers, and where you need to iterate over a fixed number of elements. It’s also useful for beginners who are just starting to learn Java.

Using Recursion: The recursion method is ideal for situations where you need to reverse small to medium-sized numbers, and where you want a clean and concise implementation. It’s also useful for more advanced Java programmers who are familiar with recursion.

In this blog of “Reverse a number in Java, we discussed several methods to reverse a number in Java, including loops, StringBuilder, and recursion. It also discussed the pros and cons of each method to help choose the best approach while reversing numbers in Java.

Our blog post on “Reverse a Number in Java” is intended to help you with any Java-related questions you may have. As you continue to develop your coding skills, visit the  Newtum‘s website to learn more about our online coding courses in Java, Python, PHP, and other topics. With practice and dedication, you can master Java development and learn new programming concepts.

About The Author

Leave a Reply