Recursive program to check if number is palindrome or not
Last Updated :
05 Sep, 2022
Given a number, the task is to write a recursive function that checks if the given number is a palindrome or not.
Examples:
Input: 121Output: yes
Input: 532Output: no
The approach for writing the function is to call the function recursively till the number is wholly traversed from the back. Use a temp variable to store the reverse of the number according to the formula obtained in this post. Pass the temp variable in the parameter and once the base case of n==0 is achieved, return temp which stores the reverse of a number. Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int rev(int n, int temp)
{
if (n == 0)
return temp;
temp = (temp * 10) + (n % 10);
return rev(n / 10, temp);
}
int main()
{
int n = 121;
int temp = rev(n, 0);
if (temp == n)
cout << "yes" << endl;
else
cout << "no" << endl;
return 0;
}
Java
import java.io.*;
class GFG
{
static int rev(int n, int temp)
{
if (n == 0)
return temp;
temp = (temp * 10) + (n % 10);
return rev(n / 10, temp);
}
public static void main (String[] args)
{
int n = 121;
int temp = rev(n, 0);
if (temp == n)
System.out.println("yes");
else
System.out.println("no" );
}
}
Python3
def rev(n, temp):
if (n == 0):
return temp;
temp = (temp * 10) + (n % 10);
return rev(n // 10, temp);
n = 121;
temp = rev(n, 0);
if (temp == n):
print("yes")
else:
print("no")
C#
using System;
class GFG
{
static int rev(int n,
int temp)
{
if (n == 0)
return temp;
temp = (temp * 10) +
(n % 10);
return rev(n / 10, temp);
}
public static void Main ()
{
int n = 121;
int temp = rev(n, 0);
if (temp == n)
Console.WriteLine("yes");
else
Console.WriteLine("no" );
}
}
PHP
<?php
function rev($n, $temp)
{
if ($n == 0)
return $temp;
$temp = ($temp * 10) + ($n % 10);
return rev($n / 10, $temp);
}
$n = 121;
$temp = rev($n, 0);
if ($temp != $n)
echo "yes";
else
echo "no";
?>
Javascript
<script>
function rev(n, temp)
{
if (n == 0)
return temp;
temp = (temp * 10) + (n % 10);
return rev(Math.floor(n / 10), temp);
}
let n = 121;
let temp = rev(n, 0);
if (temp == n)
document.write("yes" + "<br>");
else
document.write("no" + "<br>");
</script>
Time complexity: O(log10 N), as we require digits in the given number N.Auxiliary space: O(log10 N), for using recursive stack space.
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...