Tutorials

Java Basic Programs


Reverse Number


In this tutorial, our task is:

  • to reverse the given number
  • print the reversed number

Example:

Give number: 1345

Reverse number: 5431

 

Java program to reverse the given number.



public class ReverseNumber {

      public static void main(String[] args) {

            int n = 1345;
            int reverse=0; 

            while(n!=0){
                  reverse = reverse*10 + n%10;
                  n = n/10;
            }

            System.out.println(reverse);
      }
}

OUTPUT

5431

 

How the above code works?

We have number, n = 1345

We have another variable reverse purposefully assigned a initial value 0.

Till n is not zero, the while loop will continue to operate. Let's see its processing methodology:

 

1st iteration: Since 1345!=0 is true, so control enters loop.

Now we have,

reverse = reverse*10 + n%10;

reverse = 0*10 + 1345%10

reverse = 0 + 5;

reverse = 5;

 

Next operation is, n = n/10;

n = 1345/10

n = 134

 

2nd iteration: Now n = 134 and since 134!=0 is true, so control enters loop.

reverse = 5*10 + 134%10;

reverse = 50 + 4;

reverse = 54;

 

Next operation is, n = n/10

n = 134/10

n= 13;

 

3rd iteration: Now n = 13 and since 13!=0 is true, so control enters loop.

reverse = 54*10 + 13%10

reverse = 540 + 3

reverse = 543

 

Next operation is, n = n/10;

n = 13/10

n = 1;

 

4th iteration: Now n = 1 and since 1!=0 is true, so control enters loop.

reverse = 543*10 + 1%10;

reverse = 543 +1;

reverse = 5431;

 

Next operation is, n = n/10;

n = 1/10;

n = 0;

 

5th iteration: Now n = 0 and since 0!=0 is false, so control doesnot pass inside while loop and it ends.

The value of reverse is printed: 5431 which is the reverse of the given number.



Please Share this page
Views : 102
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!