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
advertisement

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

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.