Java Program to Find Reverse of a Number Using Recursion
Last Updated :
12 Mar, 2024
Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved.
To solve any problem using recursion, we should simply follow the below steps:
- Step 1: Assume the smaller problem from the problem that is similar to the bigger/original problem.
- Step 2: Decide the answer to the smallest valid input or smallest invalid input which would act as our base condition.
- Step 3: Approach the solution and link the answer to the smaller problem given by the recursive function to find the answer to the bigger/original problem using it.
Example:
Input: 14689
Output: 98641Input: 7654321
Output: 1234567
Approach 1:
- In this approach, we can simply print the unit digit of a number.
- And then call the recursive function for the number after removing this unit digit (number/10)
- And this process continues till the number is reduced to a single-digit number.
Example:
num = 82695
reverse(82695)
|
|__print(5)
reverse(8269)
|
|__print(9)
reverse(826)
|
|__print(6)
reverse(82)
|
|__print(2)
reverse(8)
|
|__print(8)
return
Java
// Java program to reverse
// an integer recursively
class GFG {
// Recursive function to print
// the number in reversed form
public static void Reverse(int num)
{
// base condition to end recursive calls
if (num < 10) {
System.out.println(num);
return;
}
else {
// print the unit digit of the given number
System.out.print(num % 10);
// calling function for remaining number other
// than unit digit
Reverse(num / 10);
}
}
// driver code
public static void main(String args[])
{
// number to be reversed
int num = 98765;
System.out.print("Reversed Number: ");
// calling recursive function
// to print the number in
// reversed form
Reverse(num);
}
}
Time complexity: O(log10n) where n is given input number.
Auxiliary space: O(1)
Approach 2:
- In this approach, we can simply maintain a variable in which we can store the number reversed till now.
- We can do this by extracting a unit digit from the number and then adding this extracted integer into the reversed number.
- But the key factor here is that we have to multiply the reversed number by 10 before adding this extracted number to the reversed number.
Example:
num = 48291
ans = 0 -> variable to store reversed number
How this works:
reverse(num)
|
|__ temp = num % 10 -> extracting unit digit from number
ans = ans*10 + temp -> adding temp at unit position in reversed number
reverse(num/10) -> calling function for remaining number
Implementation:
reverse(48291)
|
|__ temp=1
ans= 0*10 + 1 --> ans=1
reverse(4829)
|
|__ temp=9
ans= 1*10 + 9 --> ans=19
reverse(482)
|
|__ temp= 2
ans= 19*10 +2 --> ans=192
reverse(48)
|
|__ temp=8
ans=192*10 + 8 --> ans=1928
reverse(4)
|
|__ temp=4
ans=1928*10 +4 --> ans=19284
reverse(0)
|
|__ return ans
Java
// Java program to reverse an integer recursively
class GFG {
// Variable to store reversed
// number after every
// recursive call
static int ans = 0;
static int Reverse(int var)
{
// base condition to end the
// recursive calling of function
if (var == 0) {
// We have reversed the
// complete number and
// stored in ans variable
return ans;
}
if (var > 0) {
// temp variable to store the digit at unit
// place in the number
int temp = var % 10;
// Add this temp variable in the ans variable
// which stores the number reversed till now
ans = ans * 10 + temp;
// recursive calling of function to reverse the
// remaining number
Reverse(var / 10);
}
// returning final answer when the number is
// reversed completely
return ans;
}
public static void main(String[] args)
{
// Number to be reversed
int var = 98765;
// Variable to store reversed number returned by
// reverse function
int rev;
// Calling reverse function and storing the return
// value in rev variable
rev = Reverse(var);
// Printing the Reversed Number
System.out.println("Reversed number: " + rev);
}
}
Time complexity: O(logn) where n is input number to be reversed.
Auxiliary space: O(1)
Note: Java does not throw an exception when an overflow occurs so a problem of overflow might occur if the reversed number is greater than Integer.MAX_VALUE (2147483647) in method 2 but there will be no such problem in method 1.
Approach 3:
While using recursion we can look at the number of digits and using that we can concatenate the reversed numbers.
Java
import java.io.*;
import java.lang.*;
class GFG {
public int reverseDigits(int number)
{
if (number < 10)
return number;
int remainder = number % 10;
int reversedNumber
= this.reverseDigits(number / 10);
int numberOfDigits = (int)Math.log10(number) + 1;
return remainder
* (int)Math.pow(10, numberOfDigits - 1)
+ reversedNumber;
}
public static void main(String[] args)
{
GFG obj = new GFG();
int reversedNumber1 = obj.reverseDigits(987);
int reversedNumber2 = obj.reverseDigits(144321);
System.out.println(reversedNumber1);
System.out.println(reversedNumber2);
}
}
Similar Reads
Java Program to Find Sum of N Numbers Using Recursion Recursion is a process by which a function calls itself repeatedly till it falls under the base condition and our motive is achieved. To solve any problem using recursion, we should simply follow the below steps: Assume/Identify the smaller problem from the problem which is similar to the bigger/ori
4 min read
Java Program to Reverse a Sentence Using Recursion A sentence is a sequence of characters separated by some delimiter. This sequence of characters starts at the 0th index and the last index is at len(string)-1. By reversing the string, we interchange the characters starting at 0th index and place them from the end. The first character becomes the la
2 min read
Reverse Number Program in Java In Java, reversing a number means that the digit at the first position should be swapped with the last digit, the second digit will be swapped with the second last digit, and so on, till the middle element.Example of reversing a number:Input: n = 357Output: 753Input n = 100Output: 1 ( leading zeros
3 min read
Java Program to Reverse a Number and find the Sum of its Digits Using do-while Loop Problem Statement: The number is supposed to be entered by the user be it any random number lying within the primitive data-type holding the number. First, the number needs to be reversed. Secondary the sum of the number is to be calculated with the constraint to use a do-while loop. do-while loop:
6 min read
Java Program to Reverse a String using Stack The Stack is a linear data structure that follows the LIFO(Last In First Out) principle, i.e, the element inserted at the last is the element to come out first. Approach: Push the character one by one into the Stack of datatype character.Pop the character one by one from the Stack until the stack be
2 min read
Java Program to Reverse a List Reversing a list means after reversing the list, the first element should be swapped with the last element, the second element should be swapped with the second last element, and so on till the middle element and the resultant list is the reversed list. Example: Input: "PLATFORM", "LEARNING", "BEST"
3 min read
Java Program For Reversing A Linked List In Groups Of Given Size - Set 1 Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Example: Input: 1->2->3->4->5->6->7->8->NULL, K = 3 Output: 3->2->1->6->5->4->8->7->NULL Input: 1->2->3->4->5->6->7->8->NULL, K = 5 Output: 5->4->3->2->1->8->7->6->NULL Recommended: Please solve
3 min read
Java Program for Reverse a linked list Given a pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing links between nodes. Examples: Input: Head of following linked list 1->2->3->4->NULLOutput: Linked list should be changed to, 4->3->2->1->NULL In
3 min read
Java Program To Recursively Linearly Search An Element In An Array Given an array arr[] of n elements, write a recursive function to search for a given element x in the given array arr[]. If the element is found, return its index otherwise, return -1.Input/Output Example:Input : arr[] = {25, 60, 18, 3, 10}, Element to be searched x = 3Output : 3 (index )Input : arr
3 min read
Java Program For Printing Reverse Of A Linked List Without Actually Reversing Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorit
2 min read