How to reverse any number using core java concepts

In this example we are going to write a java program which will enable us to enter any integer value using Scanner object. In while loop we are going to reverse the entered number.


import java.util.Scanner;

class ReverseNumber {
    public static void main(String args[]) {
        int original, reverse = 0;

        System.out.print("Enter the number to reverse: ");
        Scanner in = new Scanner(System.in);
        original = in.nextInt();

        while (original != 0) {
            reverse = reverse * 10;
            reverse = reverse + original % 10;
            original = original / 10;
        }

        System.out.println("Reverse of entered number is: " + reverse);
    }
}


Output:

Enter the number to reverse: 123
Reverse of entered number is: 321

No comments:

Post a Comment