Java program to reverse a number

How to reverse a number?

Take a number “num”.

  1. Initialize rev_num = 0.
  2. Loop while num > 0
    (a) Multiply rev_num by 10 and add remainder of num
    divide by 10 to rev_num
    rev_num = rev_num*10 + num%10;
    (b) Divide num by 10.
  3.  Return rev_num

Java Program to reverse a number:

import java.util.Scanner;
class ReverseNumber
{
   public static void main(String args[])
   {
      int num=0;
      int reversenum =0;
      System.out.println("Input your number and press enter: ");
      //This statement will capture the user input
      Scanner in = new Scanner(System.in);
      //Captured input would be stored in number num
      num = in.nextInt();
      //While Loop: Logic to find out the reverse number
      while( num != 0 )
      {
          reversenum = reversenum * 10;
          reversenum = reversenum + num%10;
          num = num/10;
      }

      System.out.println("Reverse of input number is: "+reversenum);
   }
}

OUTPUT:

Input your number and press enter:
4562
Reverse of input number is: 2654

Let’s dry run an example:

num = 4562
rev_num = 0

rev_num = rev_num *10 + num%10 = 2
num = num/10 = 456

rev_num = rev_num *10 + num%10 = 20 + 6 = 26
num = num/10 = 45

rev_num = rev_num *10 + num%10 = 260 + 5 = 265
num = num/10 = 4

rev_num = rev_num *10 + num%10 = 265 + 4 = 2654
num = num/10 = 0

 

There is another way of reversing a number using Recursion.

Lets see how to implement a java program to reverse a number using recursion.

PROGRAM:

import java.util.Scanner;
class RecursionReverseDemo
{
   //A method for reverse
   public static void reverseMethod(int number) {
       if (number < 10) {
       System.out.println(number);
       return;
       }
       else {
           System.out.print(number % 10);
           //Method is calling itself: recursion
           reverseMethod(number/10);
       }
   }
   public static void main(String args[])
   {
    int num=0;
    System.out.println("Input your number and press enter: ");
    Scanner in = new Scanner(System.in);
    num = in.nextInt();
    System.out.print("Reverse of the input number is:");
    reverseMethod(num);
    System.out.println();
   }
}

 

OUTPUT:

Input your number and press enter:
8901
Reverse of the input number is:1098

 

Leave a Reply