How to reverse a number in Java?

The reverse of a given number is simply called as when the number is 123, the reverse number should be 321. In java, there are multiple ways to calculate the reverse of a given number. Here we will discuss a simple way using a while loop.

Follow the below steps to calculate the reverse of a number,

  1. First find the last digit of given number (calculating the remainder by dividing the number by 10).
  2. Now multiply the variable reverse by 10 and add the calculated remainder of previous step.
  3. Remove the last digit from the number by dividing the number by 10.
  4. Repeat the above 3 steps inside while loop until the number become 0.

Let’s see the complete logic to calculate the reverse of a given number,

Solution

ReverseNumber.java

package com.javacodepoint.programs;

import java.util.Scanner;

public class ReverseNumber {

	public static void main(String[] args) {

		// Taking input from the user to reverse
		
		System.out.print("Enter an integer number:");

		// Reading user input using Scanner object
		int number = new Scanner(System.in).nextInt();
		
		//Initiating reverse variable with 0 
		int reverse = 0;
		int tempNumber = number;
		
		// while loop will continue until the number become 0
		while(number > 0) {
			
			//Finding the last digit of the number
			int remainder = number % 10;
			
			//Calculating the reverse by multiplying it with 10 and adding remainder (last digit) 
			reverse = reverse * 10 + remainder;
			
			//Removing the last digit from the number
			number = number / 10;
		}
		
		System.out.print("The reverse of the given number is = "+reverse);

	}

}

OUTPUT:

Enter an integer number: 12345
The reverse of the given number is = 54321

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework