A blog for everybody who loves coding.

program to reverse a number in java

java program

in this post we will see how to write a program to reverse a number in java .

import java.util.Scanner;
class ReversedNumber
{
   public static void main(String args[]){
       Scanner in=new Scanner(System.in);
       System.out.println("enter the number");
       int n= in.nextInt();
       int reverse=0;
       while(n>0){
          int lastDigit=n%10;
          reverse=reverse*10+lastDigit;
          n/=10;
       }
       System.out.println("The reversedNumber is "+""+reverse);
    }
}

After executing the above program you will get-

enter the number
123
The reversedNumber is 321

How the above program works

when we run the program the loop executes the statement in following steps-

  • In first step the reminder of number (stored in n) stored in the variable named as lastDigit.
  • Then in the second step we add the lastDigit with reverse*10.
  • Then in last step we divide the variable n with 10.

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on whatsapp
WhatsApp

Siddharth Pandey

Programming content creator

Hi! My name is Siddharth Pandey. I am a passionate programmer, and I’m very passionate and dedicated to my work. I am a computer science student.

Web Development
EXPLORE