Reverse of n digit number in Java


This Java code defines a class reverse_number that contains a main method. The main method prompts the user to enter a number and reads the input using a Scanner object. The code then reverses the number entered by the user using a while loop.

Inside the loop, the code extracts the last digit of the number entered by the user using the modulus operator % and stores it in the variable rem. It then updates the value of reverse by multiplying it by 10 and adding rem to it. Finally, it updates the value of n by dividing it by 10 and discarding the remainder.

The loop continues until n becomes 0, at which point the entire number has been reversed. The code then prints the reversed number using the System.out.println method.

Source Code

import java.util.Scanner;
public class reverse_number {
    //Write a program to find the reverse of N digit Number
    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter The Number : ");
        int n = in.nextInt();
        int reverse=0, rem;
        while(n!=0)
        {
            rem=n%10;
            reverse=(reverse*10)+rem;
            n=n/10;
        }
        System.out.println("Reversed Number: "+reverse);
    }
}
 

Output

Enter The Number : 52967
Reversed Number: 76925
To download raw file Click Here

Basic Programs