Google News
logo
Java Program to Reverse a Numbers
The Following example of Java program to reverse a number :
Program :
import java.util.Scanner;

public class ReverseNumber {
   public static void main(String args[]){
      int num, reversedNum = 0;
      Scanner sc = new Scanner(System.in);

      System.out.println("Enter a number:");
      num = sc.nextInt();

      while(num != 0) {
         int digit = num % 10;
         reversedNum = reversedNum * 10 + digit;
         num /= 10;
      }

      System.out.println("Reversed Number: " + reversedNum);
   }
}
Output :
Enter a number:123456789
Reversed Number: 987654321
Explanation :

* We first declare two integer variables num and reversedNum and initialize reversedNum to 0.

* We then create an object of the Scanner class to read input from the user.

* We prompt the user to enter a number and read it using the nextInt() method of the Scanner class.

* We then use a while loop to reverse the number.

* Inside the while loop, we get the last digit of the number using the modulo operator (%) and store it in the variable digit.

* We then multiply reversedNum by 10 and add digit to it to reverse the number.

* Finally, we update the value of num by dividing it by 10 to discard the last digit.

* Once the while loop completes, we print the reversed number using System.out.println().