How to Reverse a number in Java

In this context, we are going to learn how to reverse a number in Java. Here is an example program so that you can understand it easily. Hope this will be helpful to you.
so the user has to Enter the Number

eg if the input is 71 so the output will be 17

Java program to reverse a number in Java

import java.util.Scanner;
 
class revNum
{
   public static void main(String args[])
   {
      int number,num;
      int revOfNumber = 0;
         
      System.out.println("Enter a number :");
      Scanner in = new Scanner(System.in);
      number = in.nextInt();
  num=number;
         
      while(number != 0)
      {
          revOfNumber = revOfNumber * 10;
          revOfNumber = revOfNumber + number%10;
          number = number/10;
      }
       
      System.out.println("The Reverse of the number "+num+" is " + revOfNumber);
   }
}

 

OUTPUT:

Enter a number : 71
The Reverse of the number 71 is 17

Explanation of Code:

Here we have initialized a class name revNum which include the main method so here we have taken mainly three variable number which takes the input from the user,revOfNumber is initialized to zero further the result will be stored in it and num variable for storing the initial number. In the code, we are fetching the last digit and storing in revOfNumber and printing it.

You may also read these:

Leave a Reply

Your email address will not be published. Required fields are marked *