How to Reverse Number by Java Program?


Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
   public static void main(String args[])
   {
      int n, reverse = 0;

      System.out.println("Enter the integer number to reverse");
      Scanner in = new Scanner(System.in);
      n = in.nextInt();

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

      System.out.println("Reverse of entered integer number is "+reverse);
   }
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

 

 

More

For more Algorithms and Java Programing Test questions and sample code follow below links

 

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Algorithm, Java, Programming Test and tagged , , . Bookmark the permalink.

One Response to How to Reverse Number by Java Program?

  1. Pingback: Frequently Asked Algorithms and Programs in Interviews | Facing Issues On IT

Comments are closed.