Write a java program to find the reverse of a given number using recursion

Write a java program to find the reverse of a given number using recursion. This is a Java program that uses recursion to find the reverse of a number. As an input, you can use any integer number. The amount of digits in the given input is then counted. The specified integer, together with its length, is sent to the other function, which returns the reverse of that number using recursion.

import static java.lang.StrictMath.pow;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int n, count = 0, m;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number");
n = s.nextInt();
m = n;
while(m > 0)
{
count++;
m = m / 10;
}
Main obj = new Main();
int a = obj.reverse(n, count);
System.out.println("Reverse"+a);
}
int reverse(int x, int length)
{
if(length == 1)
{
return x;
}
else
{
int b = x % 10;
x = x / 10;
return (int) ((b * pow(10, length - 1)) + reverse(x, --length));
}
}
}

 

Output:

Enter the number 45
Reverse 54

Why do we use recursion in java program

When a recursive function calls itself, memory for the called function is placed on top of memory for the calling function, and each function call creates a new copy of local variables. Let’s use a basic function as an example of how recursion works. Recursion is designed to solve issues that can be broken down into smaller, more repeatable ones. 

It’s especially useful for dealing with problems that have a lot of potential branches yet are too complex to be solved by iteration. Searching across a file system is a nice illustration of this. Recursion is designed to solve issues that can be broken down into smaller, more repeatable ones.

What is count() keyword in java program

The count() function in Java returns the number of elements in the stream. We can also use the Collectors. counting() function to count the number of elements in a stream. The method count() is a terminal operation.