Java Program to Reverse a Number using Recursion

This is a Java Program to Find Reverse of a Number using Recursion.

Enter any integer number as an input. After that we count the number of digits in the given input. The given number along with length of that number is passed to the other function where by using recursion we get the reverse of a number as an output.

Here is the source code of the Java Program to Find Reverse of a Number using Recursion. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import static java.lang.StrictMath.pow;
  2. import java.util.Scanner;
  3. public class Reverse_Recursion 
  4. {
  5.     public static void main(String[] args) 
  6.     {
  7.         int n, count = 0, m;
  8.         Scanner s = new Scanner(System.in);
  9.         System.out.print("Enter the number:");
  10.         n = s.nextInt();
  11.         m = n;
  12.         while(m > 0)
  13.         {
  14.             count++;
  15.             m = m / 10;
  16.         }
  17.         Reverse_Recursion obj = new Reverse_Recursion();
  18.         int a = obj.reverse(n, count);
  19.         System.out.println("Reverse:"+a);
  20.     }
  21.     int reverse(int x, int length)
  22.     {
  23.         if(length == 1)
  24.         {
  25.             return x;
  26.         }
  27.         else
  28.         {
  29.             int b = x % 10;
  30.             x = x / 10;
  31.             return (int) ((b * pow(10, length - 1)) + reverse(x, --length));
  32.         }
  33.     }
  34. }

Output:

$ javac Reverse_Recursion.java
$ java Reverse_Recursion
 
Enter the number:467
Reverse:764

Sanfoundry Global Education & Learning Series -– 1000 Java Programs.

advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.