Java Program to Find Reverse of 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.

advertisement
  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 Reference Books in Java Programming, Data Structures and Algorithms.

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!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter