Write a Java program to reverse a given number using recursion


The program takes an integer input from the user, calculates its length, and reverses the digits of the input number.

It does this using a recursive function reverseNumber() which takes two parameters: dig and len. dig is the input number, and len is the number of digits in the input number.

The function first checks if len is not 1. If len is not 1, it calculates the last digit of the input number dig using the modulus operator and multiplies it with 10 raised to the power of len-1. This will give the last digit in the correct position in the reversed number. The function then calls itself recursively with the input number dig divided by 10 to remove the last digit, and decrements len by 1. The function keeps doing this until len becomes 1. Once len becomes 1, the function returns dig, which is the last remaining digit in the input number.

The reversed number is then stored in the variable res and printed to the console.

Source Code

import java.util.*;
public class Reverse
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int dig,t = 0,len = 0,res;
		System.out.printf("Enter the Digits : ");
		dig = input.nextInt();
		t = dig;
		while (t > 0)
		{
			t = t / 10;
			len = len + 1;
		}
		res = reverseNumber(dig, len);
		System.out.printf("Reverse Digits : " + res);
	}
	public static int reverseNumber(int dig, int len) 
	{
		if (len != 1)
		{
			return (((dig % 10) * (int) Math.pow(10, len - 1)) + reverseNumber(dig / 10, --len));
		}
		return dig;
	}
}

Output

Enter the Digits : 12345
Reverse Digits : 54321