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

 

Advertisements

One thought on “How to Reverse Number by Java Program?”

This site uses Akismet to reduce spam. Learn how your comment data is processed.