Java Program to Reverse a Number

In this program we will learn to reverse any number wsing for loop and while loop.

Ex: 12345 -> 54321

Method 1: Reverse a Number using a while loop in Java

public class ReverseNumber {

    public static void main(String[] args) {

        int num = 1234, reversed = 0;

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

        System.out.println("Reversed Number: " + reversed);
    }
}

Output:

Reversed Number: 4321

Method 2: Reverse a number using a for loop in Java

public class ReverseNumber {

    public static void main(String[] args) {

        int num = 1234567, reversed = 0;

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

        System.out.println("Reversed Number: " + reversed);
    }
}

Output

Reversed Number: 7654321

Leave a Reply