Reverse of a number in Java

Java Program to display reverse of a number

In the following question, we are supposed to ask the user for an Integer input and then display the mirror image or reverse of the number.

Suppose the number is 123456, thus 654321 is the reverse of the number.

The standard algorithm will be:

  1. Enter and Store the Integer Input.
  2. Store the same input in a duplicate variable for later use.
  3. Use a While loop which will run until N is reduced to 0.
  4. Construct to extract each individual digit from the extreme right.
  5. Keep Accumulating it in a separate variable within the loop construct.
  6. After the loop terminates, finally print the result as the reverse number.

Source Code:

/* Program to display reverse or mirror of a number. */

import java.util.*; class NumReverse { public static void main() { Scanner inp=new Scanner(System.in); System.out.print("\n Enter Number: "); int n=inp.nextInt(); int a,s=0,m=n;

while(n!=0) // Extracting each digits and accumulating its sum. { a=n%10; s=s*10+a; n=n/10; }

System.out.println("Reverse of "+m+" is: "+s);

} }

Output:

Enter Number: 356213
Reverse of 356213 is: 312653
Reverse of a number in Java