Reverse a Number in Java

In this program we will reverse a number in java using for loop , while loop and recursion .Reversing a number means swap first element with last element and second element with second last element and so on till the middle element . In this article we will see various ways for java program to reverse a number as following .

1.  Reverse a Number using while loop                                                                                     2.  Reverse a Number Using For loop                                                                                       3.  Reverse a Number Using Recursion

Reverse a Number Using while loop

Now we will write a program in java to reverse the digits of a number using while loop . In this program first we will add reminder of number num in reverse which is initialize by zero .In second step we will assign value of num/10 to number num and so on.

public class ReverseNumber {

	public static void main(String[] args) {
		int num = 251;
		int reverse = 0;
		while (num > 0) {
			reverse = reverse * 10 + num % 10;
			num = num / 10;
		}
		System.out.println("reverse number is =" + reverse);
	}
}

Output:

reverse number is =152

Reverse a Number Using For loop

We will write a program to reverse a number in java using for loop. We will use same logic as above only replace while loop with for loop.

public class ReverseNumber {

	public static void main(String[] args) {
		int num = 251;
		int reverse = 0;
		for ( ; num != 0 ; num/=10) {
			reverse = reverse * 10 + num % 10;
		}
		System.out.println("reverse number is =" + reverse);
	}

}

Output:

reverse number is =152

We have written programs to reverse a number in java without using built in methods. We have used loop to reverse the number in java . In next way we see how to reverse a number in java without using loop .

Reverse a Number Using Recursion

Now we will reverse a number using recursion in java .

public class ReverseNumberByRec {
	public static void main(String[] args) {
		int num = 251;
		System.out.println("reverse number is =" + reverseNumber(num));
	}

	static int reverse = 0;

	private static int reverseNumber(int num) {

		if (num > 0) {
			reverse = reverse * 10 + num % 10;
			reverseNumber(num /= 10);
		}
		return reverse;
	}

}

Output:

reverse number is =152

In this article we have seen various program to reverse a number in java . You can see Top java coding programs with answer. You can learn also how to reverse string in java with good example.

Leave a Reply

Your email address will not be published. Required fields are marked *

47 − 45 =