📜  递归程序检查数字是否为回文

📅  最后修改于: 2021-05-04 07:52:55             🧑  作者: Mango

给定一个数字,任务是编写一个递归函数,以检查给定的数字是否是回文。
例子:

Input : 121
Output : yes

Input : 532
Output : no

编写函数的方法是递归调用函数,直到从背面完全遍历数字为止。使用临时变量根据在此帖子中获得的公式存储数字的倒数。在参数中传递temp变量,一旦实现n == 0的基本情况,则返回temp,该temp存储数字的倒数。
下面是上述方法的实现:

C++
// Recursive C++ program to check if the
// number is palindrome or not
#include 
using namespace std;
 
// recursive function that returns the reverse of digits
int rev(int n, int temp)
{
    // base case
    if (n == 0)
        return temp;
 
    // stores the reverse of a number
    temp = (temp * 10) + (n % 10);
 
    return rev(n / 10, temp);
}
 
// Driver Code
int main()
{
 
    int n = 121;
     
    int temp = rev(n, 0);
   
    if (temp == n)
        cout << "yes" << endl;
    else
        cout << "no" << endl;
    return 0;
}


Java
// Recursive Java program to
// check if the number is
// palindrome or not
import java.io.*;
 
class GFG
{
 
// recursive function that
// returns the reverse of digits
static int rev(int n, int temp)
{
    // base case
    if (n == 0)
        return temp;
 
    // stores the reverse
    // of a number
    temp = (temp * 10) + (n % 10);
 
    return rev(n / 10, temp);
}
 
// Driver Code
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" );
}
}
 
// This code is contributed by anuj_67.


Python3
# Recursive Python3 program to check
# if the number is palindrome or not
 
# Recursive function that returns
# the reverse of digits
def rev(n, temp):
 
    # base case
    if (n == 0):
        return temp;
 
    # stores the reverse of a number
    temp = (temp * 10) + (n % 10);
 
    return rev(n / 10, temp);
 
# Driver Code
n = 121;
temp = rev(n, 0);
 
if (temp != n):
    print("yes");
else:
    print("no");
 
# This code is contributed
# by mits


C#
// Recursive C# program to
// check if the number is
// palindrome or not
using System;
 
class GFG
{
 
// recursive function
// that returns the
// reverse of digits
static int rev(int n,
               int temp)
{
    // base case
    if (n == 0)
        return temp;
 
    // stores the reverse
    // of a number
    temp = (temp * 10) +
               (n % 10);
 
    return rev(n / 10, temp);
}
 
// Driver Code
public static void Main ()
{
    int n = 121;
    int temp = rev(n, 0);
     
    if (temp == n)
        Console.WriteLine("yes");
    else
        Console.WriteLine("no" );
}
}
 
// This code is contributed
// by anuj_67.


PHP


Javascript


输出:
yes