Java Program to Reverse a Number

Here you will get java program to reverse a number with while loop and recursion.

When we divide a number with 10 then the remainder is the last digit of number and quotient is the number without last digit. / operator is used find quotient and % operator is used to find remainder. We use this concept to reverse the number.

Example:

Initially n = 123, reverse = 0

Step 1:

remainder = n % 10 = 123 % 10 = 3

reverse = (reverse * 10) + remainder = (0 * 10) + 3 = 3

n = n / 10 = 123 / 10 = 12

Step 2:

remainder = n % 10 = 12 % 10 = 2

reverse = (reverse * 10) + remainder = (3 * 10) + 2 = 32

n = n / 10 = 12 / 10 = 1

Step 3:

remainder = n % 10 = 1 % 10 = 1

reverse = (reverse * 10) + remainder = (32 * 10) + 1 = 321

n = n / 10 = 1 / 10 = 0

We repeat above steps until n becomes 0. Finally reverse of number is obtained.

Java Program to Reverse a Number

Using While Loop

import java.util.Scanner;

public class JavaReverseNumber {
	public static void main(String...s){
		int n,reverse = 0,remainder;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a number:");
		n = sc.nextInt();
		
		while(n!=0){
			remainder = n%10;
			reverse = (reverse * 10) + remainder;
			n = n/10;
		}
		
		System.out.println("Reverse of number is " + reverse);
	}
}

 

Output

Enter a number:
1159
Reverse of number is 9511

 

Using Recursion

import java.util.Scanner;

public class JavaReverseNumber {
	public static void main(String...s){
		int n,reverse = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a number:");
		n = sc.nextInt();
		
		reverse = reverseNumber(n, reverse);
		System.out.println("Reverse of number is " + reverse);
	}
	
	static int reverseNumber(int n, int reverse){
		int remainder;
		
		if(n == 0){
			return reverse;
		}
	
		remainder = n%10;
		reverse = (reverse * 10) + remainder;
		
		return reverseNumber(n/10, reverse);
	}
}

 

Output

Enter a number:
8764
Reverse of number is 4678

 

Comment below if you have doubts or found anything incorrect in above java program to reverse a number.

 

Leave a Comment

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