Reversing a number in Java is a process of alternating the given order of numbers or digits. However, it is not that the alternate order would be random, the program will change the order according to a sequence, where the first number would swap with the last digit in the order.

For example, if the original number is 5678, its reverse number would be 8765, which is exactly a mirror image of the original number. There are several methods to reverse a number in Java, which we will discuss in the following article to increase your understanding. These methods include the algorithm and Java code to reverse a number in Java. 

What is Reverse a Number in Java?

Reverse a number in Java simply means swapping the numbers with each other. In Java, you swap the first number with the last digit, the second number with the second last digit, and the third number with the third last image until you reach the middle elements.

There are several programming scenarios where reversing the number is applicable and useful, such as:

  • To solve any mathematical Problem

  • To manipulate the numeric data

  • To check the palindromic number

In the following blog, we will discuss how to reverse a number in Java using multiple methods. Keep coding with us.

Logical Solution to Reverse the Number in Java

Problem Statement

Take any number given that you have to reverse in Java.

Solution

Following are the processing steps to approach the required result.

  • First, you have, to initialize a variable called “reverseNumber” to store the reverse number. 

  • Secondly, take any given number that is greater than zero.

  • Then, take the remainder of the original number by using the modulo operator (%)

  • Multiply the variable “reverseNumber” by 10

  • Then add the remainder in the variable 

  • The next step is to eliminate the least significant digit by dividing the original number by 10

  • Repeat all the steps until the given number turns to zero

The Formula is 

 

Five Ways to Reverse the Number in Java

We are going to discuss five different ways to write a Java program for reverse numbers. You can use the following methods:

  1. While Loop

  2. Do While Loop

  3. Recursion

  4. String

  5. Array

We will explain each method one by one.

Reverse a Number in Java Using While Loop Method

Steps to reverse the number by using a while loop:

  • For example, if the original number is 5678, you have to create a variable “originalNumber” and set it to the original digit.

  • Initiate the while loop.

  • During each iteration of the while loop, use the modulo operator to extract the remainder or last digit. Then add the remainder to another variable called “reverseNumber” after multiplying it by 10

  • Then remove the least significant digit of the orignal number by diving it by 10

  • The loop continues until the “orignalNumber” becomes zero.

  • The output of the program will be “reverseNumber = 8765”

 

public class NumberReversal {

public static void main(String[] args) {

int originalNumber = 5678;

int reversedNumber = 0;  while (originalNumber != 0) {

int remainder = originalNumber % 10;

reversedNumber = reversedNumber * 10 + remainder;

originalNumber = originalNumber / 10;

}  System.out.println("Reversed Number: " + reversedNumber);

}

}

 

 

Reverse a Number in Java Using do-While Loop

In the do-while loop, the process will happen in the same sequence and steps as mentioned in the While loop, as you have to create two variables, “reverseNumber” and “orignalNumber.” Then using the modulo operator and do-while you can get the required output. Following is the Java code to reverse a number in Java using a do-while loop.

 

public class ReverseNumber {

public static void main(String[] args) {

int originalNumber = 5678;

int reversedNumber = 0;  do {

int remainder = originalNumber % 10;

reversedNumber = reversedNumber * 10 + remainder;

originalNumber = originalNumber / 10;

} while (originalNumber != 0);  System.out.println("Reversed Number: " + reversedNumber);

}

}



Use the Recursion Method to Reverse the Number in Java

The recursion method is different from the loops. We will discuss both the logical solution and the Java program to reverse numbers.

Logic Behind the Recursive Method

  • Step 1: Base Case

If the number is less than 10, as it is a single digit from 0 to 9, there is no need for recursion. The program will return the number as it is.

  • Step 2: Recursive Case

  1. Divide the number by 10 to find its remainder. This will provide you with the final digit of the number.

  2. Then divide this digit by 10 to remove its quotient, this will remove the last digit of the number.

  3. Then call the function “reverseNumber()” recursively as the argument with the quotient.

  4. Then, multiply the remainder by 10 by raising to the power of the number of digits in the quotient.

  5. Add the reverse value to the multiplied number that you obtained from the recursive call.

  6. And returned the sum as the reverse number.

  • Step 3: 

Recursion will continue until the reversed number is returned by the program or constructed.

Simple Formula of Recursion Method

(remainder * Math.pow(10, String.valueOf(quotient).length())) + reverseNumber(quotient);

In this formula:

  • The number represents the original number in the code

  • The remainder is the last digit, given by the modulo operator by dividing the number with 10

  • The quotient is the remaining part of the number after dividing the number by the 10

  • “reverseNumber(quotient)” represents the recursive call.

  • “Math.Pow()” is the method to call the power of 10.

What will be the output of the following program?

You will get a reverse number such as “8765” in the output which is the reverse order of “5678.”

 

public class ReverseNumber {

public static void main(String[] args) {

int originalNumber = 5678;

int reversedNumber = reverseNumber(originalNumber);  System.out.println("Reversed Number: " + reversedNumber);

}  public static int reverseNumber(int number) {

if (number < 10) {

return number;

int remainder = number % 10;

int quotient = number / 10;  return (int) (remainder * Math.pow(10, String.valueOf(quotient).length())) + reverseNumber(quotient);

}

}

 

String Java Code to Reverse a Number

See the example of writing the code for the string method.

  • Set the variable “originalNumber” variable to 5678.

  • Then call the reverse number method with the number using the function “reverseNumber()” as an argument.

  • Then convert the number to a string “string.valueOf(number)”.

  • Then reverse the representation of the number by using stringbuilder class. For this purpose we will use the method “reverse().”

  • Then convert the reversed string back to an integer by using “integer.perseInt() and return the revered number.

What will be the output of this code?

The output of this code will be “Reverse Number= 8765.”

 

public class ReverseNumber {

public static void main(String[] args) {

int originalNumber = 5678;

int reversedNumber = reverseNumber(originalNumber);  System.out.println("Reversed Number: " + reversedNumber);

}  public static int reverseNumber(int number) {

String numberString = String.valueOf(number); // Convert number to a string

String reversedString = new StringBuilder(numberString).reverse().toString(); // Reverse the string

int reversedNumber = Integer.parseInt(reversedString); // Convert the reversed string back to an integer

return reversedNumber;

}

}

 

Reverse a Number in Java by Using Arry

  • Start the program by converting the number into a string using “integer.toString(number).”

  • Then create an integer array with the named “digit” and set its length to equal to the number of digits in the string.

  • Then set the loop to extract each number from the string to add it to the array.

  • Then convert each character to an integer by using the code “Character.getNumericValue().”

  • Swap the elements by using another loop to reverse the digits.

  • Multiply each digit with an appropriate power of 10 to reverse the array back to the number and add it to the “reverseNumber” variable.

  • The output will be 8765.

 

public class ReverseNumber {

public static void main(String[] args) {

int number = 5678; // The number to be reversed 

// Convert the number to a string

String numberString = Integer.toString(number); 

// Create an array to store the digits of the number

int[] digits = new int[numberString.length()]; 

// Extract the digits from the string and store them in the array

for (int i = 0; i < numberString.length(); i++) {

digits[i] = Character.getNumericValue(numberString.charAt(i));

// Reverse the array

for (int i = 0, j = digits.length - 1; i < j; i++, j--) {

int temp = digits[i];

digits[i] = digits[j];

digits[j] = temp;

// Convert the reversed array back to a number

int reversedNumber = 0;

for (int i = 0; i < digits.length; i++) {

reversedNumber = reversedNumber * 10 + digits[i];

System.out.println("Original number: " + number);

System.out.println("Reversed number: " + reversedNumber);

}

}



 

Conclusion

As illustrated through various methods in this blog, reversing a number in Java is a fundamental yet essential task for numerous programming scenarios. By mastering these techniques, developers can enhance their problem-solving skills and better manipulate numeric data. Whether you choose to implement a while loop, a do-while loop, recursion, strings, or arrays, the logical processes remain clear and manageable.

Understanding these methods is not just an academic exercise; it's a practical skill that can be applied to real-world problems, such as solving mathematical challenges, manipulating data, or checking for palindromic numbers. The step-by-step explanations and code examples provided should enable you to confidently reverse numbers in your Java projects.

At Enfixo, we specialize in software development and offer a wide range of services tailored to meet your specific needs. Whether you're looking to develop custom applications, enhance your existing systems, or receive expert consultation on complex programming tasks, our team of experienced developers is here to help.

Contact us today to learn how we can assist you in achieving your software development goals.