Reverse the Five Digit Number in Java


If a five-digit number is input through the keyboard, write a program to reverse the number.

  • The program prompts the user to enter a five-digit integer using the Scanner class.
  • The integer is stored in the variable 'num'.
  • The program initializes two variables: 'rem' to store the remainder of the integer when divided by 10, and 'rev' to store the reversed integer.
  • The program extracts each digit of the integer using the modulo operator and integer division. It starts with the rightmost digit and moves leftward.
  • Each digit is then multiplied by a power of 10 and added to 'rev' in order to create the reversed integer.
  • Finally, the program outputs the reversed integer using the 'System.out.println()' method.

Source Code

import java.util.Scanner;
class Reverse_Digits
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the Five Digits Numbers :");
		int num = input.nextInt();
		System.out.println("Before Reverse :"+num);	
		int rem,rev=0;
		rem=num%10;
		num=num/10;
		rev=rev+rem*10000;
 
		rem=num%10;
		num=num/10;
		rev=rev+rem*1000;
 
		rem=num%10;
		num=num/10;
		rev=rev+rem*100;
 
		rem=num%10;
		num=num/10;
		rev=rev+rem*10;
 
		rem=num%10;
		rev=rev+rem;
		System.out.println("After Reverse :"+rev);
	}
}

Output

Enter the Five Digits Numbers :
58624
Before Reverse :58624
After Reverse :42685