Java program to reverse a given number using recursion

Given a number, we have to reverse it using the recursion.
Submitted by Nidhi, on June 02, 2022

Problem Solution:

In this program, we will read an integer number from the user, and then we will find the reverse of the input number using recursion.

Program/Source Code:

The source code to reverse a given number using recursion is given below. The given program is compiled and executed successfully.

// Java program to reverse a given number 
// using the recursion

import java.util.*;

public class Main {
  public static int reverseNumber(int num, int len) {
    if (len != 1)
      return (((num % 10) * (int) Math.pow(10, len - 1)) + reverseNumber(num / 10, --len));
    return num;
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);

    int num = 0;
    int tmp = 0;
    int len = 0;
    int res = 0;

    System.out.printf("Enter number: ");
    num = X.nextInt();

    tmp = num;
    while (tmp > 0) {
      tmp = tmp / 10;
      len = len + 1;
    }

    res = reverseNumber(num, len);
    System.out.printf("Reversed number is: " + res);
  }
}

Output:

Enter number: 7634
Reversed number is: 4367

Explanation:

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods reverseNumber(), main(). The reverseNumber() is a recursive method that calculates the reverse of a specified number and returns the result to the calling method.

The main() method is the entry point for the program. Here, we read an integer number from the user and called the reverseNumber() method to calculate the reverse of the input number and printed the result.

Java Recursion Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.