Given a number, the task is to write a recursive function that checks if the given number is a palindrome or not.
Examples:
Input: 121
Output: yes
Input: 532
Output: 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(log10N), as we require digits in the given number N.
Auxiliary space: O(log10N), for using recursive stack space.