📌  相关文章
📜  检查数字是否是回文

📅  最后修改于: 2021-05-04 18:26:45             🧑  作者: Mango

给定一个整数,编写一个函数,如果给定的数是回文数,则返回true,否则返回false。例如,12321是回文,但1451不是回文。

让给定的数字为num 。此问题的一个简单的方法是为num的第一反向数字,然后比较NUM NUM相反。如果两者相同,则返回true,否则返回false。
以下是从这篇文章的方法2中得到启发的有趣方法。这个想法是创建num的副本,然后按引用递归传递该副本,然后按值传递num 。在递归调用中,在递归树上移动时将num除以10。在递归树上移动时,将副本除以10。当它们在所有子调用均已结束的函数遇到时, num的最后一位将是从开头开始的第ith位,而副本的最后一位将是从后面开始的ith位。结束。

C++
// A recursive C++ program to check
// whether a given number
// is palindrome or not
#include 
 
// A function that reurns true only
// if num contains one
// digit
int oneDigit(int num)
{
     
    // Comparison operation is faster
    // than division
    // operation. So using following
    // instead of "return num
    // / 10 == 0;"
    return (num >= 0 && num < 10);
}
 
// A recursive function to find
// out whether num is
// palindrome or not. Initially, dupNum
// contains address of
// a copy of num.
bool isPalUtil(int num, int* dupNum)
{
     
    // Base case (needed for recursion
    // termination): This
    // statement mainly compares the
    // first digit with the
    // last digit
    if (oneDigit(num))
        return (num == (*dupNum) % 10);
 
    // This is the key line in this
    // method. Note that all
    // recursive calls have a separate
    // copy of num, but they
    // all share same copy of *dupNum.
    // We divide num while
    // moving up the recursion tree
    if (!isPalUtil(num / 10, dupNum))
        return false;
 
    // The following statements are
    // executed when we move up
    // the recursion call tree
    *dupNum /= 10;
 
    // At this point, if num%10 contains
    // i'th digit from
    // beiginning, then (*dupNum)%10
    // contains i'th digit
    // from end
    return (num % 10 == (*dupNum) % 10);
}
 
// The main function that uses
// recursive function
// isPalUtil() to find out whether
// num is palindrome or not
int isPal(int num)
{
     
    // Check if num is negative,
    // make it positive
    if (num < 0)
        num = -num;
 
    // Create a separate copy of num,
    // so that modifications
    // made to address dupNum don't
    // change the input number.
    // *dupNum = num
    int* dupNum = new int(num);
 
    return isPalUtil(num, dupNum);
}
 
// Driver program to test
// above functions
int main()
{
    int n = 12321;
    isPal(n) ? printf("Yesn") : printf("Non");
 
    n = 12;
    isPal(n) ? printf("Yesn") : printf("Non");
 
    n = 88;
    isPal(n) ? printf("Yesn") : printf("Non");
 
    n = 8999;
    isPal(n) ? printf("Yesn") : printf("Non");
    return 0;
}


Java
// A recursive Java program to
// check whether a given number
// is palindrome or not
import java.io.*;
import java.util.*;
  
public class CheckPallindromNumberRecursion {
  
    // A function that reurns true
    // only if num contains one digit
    public static int oneDigit(int num) {
  
        if ((num >= 0) && (num < 10))
            return 1;
        else
            return 0;
    }
  
    public static int isPalUtil
    (int num, int dupNum) throws Exception {
  
        // base condition to return once we
        // move past first digit
        if (num == 0) {
            return dupNum;
        } else {
            dupNum = isPalUtil(num / 10, dupNum);
        }
  
        // Check for equality of first digit of
        // num and dupNum
        if (num % 10 == dupNum % 10) {
            // if first digit values of num and
            // dupNum are equal divide dupNum
            // value by 10 to keep moving in sync
            // with num.
            return dupNum / 10;
        } else {
            // At position values are not
            // matching throw exception and exit.
            // no need to proceed further.
            throw new Exception();
        }
  
    }
  
    public static int isPal(int num)
    throws Exception {
  
        if (num < 0)
            num = (-num);
  
        int dupNum = (num);
  
        return isPalUtil(num, dupNum);
    }
  
    public static void main(String args[]) {
  
        int n = 1242;
        try {
            isPal(n);
            System.out.println("Yes");
        } catch (Exception e) {
            System.out.println("No");
        }
        n = 1231;
        try {
            isPal(n);
            System.out.println("Yes");
        } catch (Exception e) {
            System.out.println("No");
        }
  
        n = 12;
        try {
            isPal(n);
            System.out.println("Yes");
        } catch (Exception e) {
            System.out.println("No");
        }
  
        n = 88;
        try {
            isPal(n);
            System.out.println("Yes");
        } catch (Exception e) {
            System.out.println("No");
        }
  
        n = 8999;
        try {
            isPal(n);
            System.out.println("Yes");
        } catch (Exception e) {
            System.out.println("No");
        }
    }
}
  
// This code is contributed
// by Nasir J


Python3
# A recursive Pyhton3 program to check
# whether a given number is palindrome or not
 
# A function that reurns true
# only if num contains one digit
def oneDigit(num):
     
    # comparison operation is faster
    # than division operation. So
    # using following instead of
    # "return num / 10 == 0;"
    return ((num >= 0) and
            (num < 10))
 
# A recursive function to find
# out whether num is palindrome
# or not. Initially, dupNum
# contains address of a copy of num.
def isPalUtil(num, dupNum):
     
    # Base case (needed for recursion
    # termination): This statement
    # mainly compares the first digit
    # with the last digit
    if oneDigit(num):
        return (num == (dupNum[0]) % 10)
 
    # This is the key line in this
    # method. Note that all recursive
    # calls have a separate copy of
    # num, but they all share same
    # copy of *dupNum. We divide num
    # while moving up the recursion tree
    if not isPalUtil(num //10, dupNum):
        return False
 
    # The following statements are
    # executed when we move up the
    # recursion call tree
    dupNum[0] = dupNum[0] //10
 
    # At this point, if num%10
    # contains i'th digit from
    # beiginning, then (*dupNum)%10
    # contains i'th digit from end
    return (num % 10 == (dupNum[0]) % 10)
 
# The main function that uses
# recursive function isPalUtil()
# to find out whether num is
# palindrome or not
def isPal(num):
    # If num is negative,
    # make it positive
    if (num < 0):
        num = (-num)
 
    # Create a separate copy of
    # num, so that modifications
    # made to address dupNum
    # don't change the input number.
    dupNum = [num] # *dupNum = num
 
    return isPalUtil(num, dupNum)
 
# Driver Code
n = 12321
if isPal(n):
    print("Yes")
else:
    print("No")
 
n = 12
if isPal(n) :
    print("Yes")
else:
    print("No")
 
n = 88
if isPal(n) :
    print("Yes")
else:
    print("No")
 
n = 8999
if isPal(n) :
    print("Yes")
else:
    print("No")
 
# This code is contributed by mits


C#
// A recursive C# program to
// check whether a given number
// is palindrome or not
using System;
 
class GFG
{
     
// A function that reurns true
// only if num contains one digit
public static int oneDigit(int num)
{
    // comparison operation is
    // faster than division
    // operation. So using
    // following instead of
    // "return num / 10 == 0;"
    if((num >= 0) &&(num < 10))
    return 1;
    else
    return 0;
}
 
// A recursive function to
// find out whether num is
// palindrome or not.
// Initially, dupNum contains
// address of a copy of num.
public static int isPalUtil(int num,
                            int dupNum)
{
    // Base case (needed for recursion
    // termination): This statement
    // mainly compares the first digit
    // with the last digit
    if (oneDigit(num) == 1)
        if(num == (dupNum) % 10)
        return 1;
        else
        return 0;
 
    // This is the key line in
    // this method. Note that
    // all recursive calls have
    // a separate copy of num,
    // but they all share same
    // copy of *dupNum. We divide
    // num while moving up the
    // recursion tree
    if (isPalUtil((int)(num / 10), dupNum) == 0)
        return -1;
 
    // The following statements
    // are executed when we move
    // up the recursion call tree
    dupNum = (int)(dupNum / 10);
 
    // At this point, if num%10
    // contains i'th digit from
    // beiginning, then (*dupNum)%10
    // contains i'th digit from end
    if(num % 10 == (dupNum) % 10)
        return 1;
    else
        return 0;
}
 
// The main function that uses
// recursive function isPalUtil()
// to find out whether num is
// palindrome or not
public static int isPal(int num)
{
    // If num is negative,
    // make it positive
    if (num < 0)
    num = (-num);
 
    // Create a separate copy
    // of num, so that modifications
    // made to address dupNum
    // don't change the input number.
    int dupNum = (num); // *dupNum = num
 
    return isPalUtil(num, dupNum);
}
 
// Driver Code
public static void Main()
{
int n = 12321;
if(isPal(n) == 0)
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
 
n = 12;
if(isPal(n) == 0)
    Console.WriteLine("Yes");
else
    Console.WriteLine( "No");
 
n = 88;
if(isPal(n) == 1)
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
 
n = 8999;
if(isPal(n) == 0)
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");
}
}
 
// This code is contributed by mits


PHP
= 0) &&
            ($num < 10));
}
 
// A recursive function to find
// out whether num is palindrome
// or not. Initially, dupNum
// contains address of a copy of num.
function isPalUtil($num, $dupNum)
{
    // Base case (needed for recursion
    // termination): This statement
    // mainly compares the first digit
    // with the last digit
    if (oneDigit($num))
        return ($num == ($dupNum) % 10);
 
    // This is the key line in this
    // method. Note that all recursive
    // calls have a separate copy of
    // num, but they all share same
    // copy of *dupNum. We divide num
    // while moving up the recursion tree
    if (!isPalUtil((int)($num / 10),
                         $dupNum))
        return -1;
 
    // The following statements are
    // executed when we move up the
    // recursion call tree
    $dupNum = (int)($dupNum / 10);
 
    // At this point, if num%10 
    // contains i'th digit from
    // beiginning, then (*dupNum)%10
    // contains i'th digit from end
    return ($num % 10 == ($dupNum) % 10);
}
 
// The main function that uses
// recursive function isPalUtil()
// to find out whether num is
// palindrome or not
function isPal($num)
{
    // If num is negative,
    // make it positive
    if ($num < 0)
    $num = (-$num);
 
    // Create a separate copy of
    // num, so that modifications
    // made to address dupNum
    // don't change the input number.
    $dupNum = ($num); // *dupNum = num
 
    return isPalUtil($num, $dupNum);
}
 
// Driver Code
$n = 12321;
if(isPal($n) == 0)
    echo "Yes\n";
else
    echo "No\n";
 
$n = 12;
if(isPal($n) == 0)
    echo "Yes\n";
else
    echo "No\n";
 
$n = 88;
if(isPal($n) == 1)
    echo "Yes\n";
else
    echo "No\n";
 
$n = 8999;
if(isPal($n) == 0)
    echo "Yes\n";
else
    echo "No\n";
 
// This code is contributed by m_kit
?>


Javascript


C++14
// C++ implementation of the above aprroach
#include 
using namespace std;
 
// Function to check palindrome
int checkPalindrome(string str)
{
    // Calculating string length
    int len = str.length();
   
    // Traversing through the string
    // upto hlaf its length
    for (int i = 0; i < len / 2; i++) {
       
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str[i] != str[len - i - 1])
            return false;
    }
   
    // If the above loop doesn't return then it is
    // palindrome
    return true;
}
 
// Driver Code
int main()
{ // taking number as string
    string st
        = "112233445566778899000000998877665544332211";
    if (checkPalindrome(st) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
// this code is written by vikkycirus


Java
// Java implementation of the above aprroach
import java.io.*;
 
class GFG{
 
// Function to check palindrome
static boolean checkPalindrome(String str)
{
     
    // Calculating string length
    int len = str.length();
 
    // Traversing through the string
    // upto hlaf its length
    for(int i = 0; i < len / 2; i++)
    {
         
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str.charAt(i) !=
            str.charAt(len - i - 1))
            return false;
    }
 
    // If the above loop doesn't return then
    // it is palindrome
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Taking number as string
    String st = "112233445566778899000000998877665544332211";
     
    if (checkPalindrome(st) == true)
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by subhammahato348


Python3
# Python3 implementation of the above aprroach
 
# function to check palindrome
def checkPalindrome(str):
   
    # Run loop from 0 to len/2
    for i in range(0, len(str)//2):
        if str[i] != str[len(str)-i-1]:
            return False
           
    # If the above loop doesn't
    #return then it is palindrome
    return True
 
 
# Driver code
st = "112233445566778899000000998877665544332211"
if(checkPalindrome(st) == True):
    print("it is a palindrome")
else:
    print("It is not a palindrome")


C#
// C# implementation of the above aprroach
using System;
 
class GFG{
 
// Function to check palindrome
static bool checkPalindrome(string str)
{
     
    // Calculating string length
    int len = str.Length;
 
    // Traversing through the string
    // upto hlaf its length
    for(int i = 0; i < len / 2; i++)
    {
         
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str[i] != str[len - i - 1])
            return false;
    }
 
    // If the above loop doesn't return then
    // it is palindrome
    return true;
}
 
// Driver Code
public static void Main()
{
     
    // Taking number as string
    string st = "112233445566778899000000998877665544332211";
 
    if (checkPalindrome(st) == true)
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by subhammahato348


Javascript


输出:

Yes
No
Yes
No 

在不使用任何多余空间的情况下检查数字是否是回文
方法2:使用字符串()方法

  1. 当该数字的位数超过10 18时,由于long long int的范围不满足给定的数字,我们不能将该数字作为整数。
  2. 因此,需要输入作为字符串,从开始到长度/ 2运行的环路,并检查第一个字符(数字)到字符串的最后一个字符和第二到第二最后一个,等等。如果…任何字符不匹配,字符串不会是回文。

下面是上述方法的实现

C++ 14

// C++ implementation of the above aprroach
#include 
using namespace std;
 
// Function to check palindrome
int checkPalindrome(string str)
{
    // Calculating string length
    int len = str.length();
   
    // Traversing through the string
    // upto hlaf its length
    for (int i = 0; i < len / 2; i++) {
       
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str[i] != str[len - i - 1])
            return false;
    }
   
    // If the above loop doesn't return then it is
    // palindrome
    return true;
}
 
// Driver Code
int main()
{ // taking number as string
    string st
        = "112233445566778899000000998877665544332211";
    if (checkPalindrome(st) == true)
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
// this code is written by vikkycirus

Java

// Java implementation of the above aprroach
import java.io.*;
 
class GFG{
 
// Function to check palindrome
static boolean checkPalindrome(String str)
{
     
    // Calculating string length
    int len = str.length();
 
    // Traversing through the string
    // upto hlaf its length
    for(int i = 0; i < len / 2; i++)
    {
         
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str.charAt(i) !=
            str.charAt(len - i - 1))
            return false;
    }
 
    // If the above loop doesn't return then
    // it is palindrome
    return true;
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Taking number as string
    String st = "112233445566778899000000998877665544332211";
     
    if (checkPalindrome(st) == true)
        System.out.print("Yes");
    else
        System.out.print("No");
}
}
 
// This code is contributed by subhammahato348

Python3

# Python3 implementation of the above aprroach
 
# function to check palindrome
def checkPalindrome(str):
   
    # Run loop from 0 to len/2
    for i in range(0, len(str)//2):
        if str[i] != str[len(str)-i-1]:
            return False
           
    # If the above loop doesn't
    #return then it is palindrome
    return True
 
 
# Driver code
st = "112233445566778899000000998877665544332211"
if(checkPalindrome(st) == True):
    print("it is a palindrome")
else:
    print("It is not a palindrome")

C#

// C# implementation of the above aprroach
using System;
 
class GFG{
 
// Function to check palindrome
static bool checkPalindrome(string str)
{
     
    // Calculating string length
    int len = str.Length;
 
    // Traversing through the string
    // upto hlaf its length
    for(int i = 0; i < len / 2; i++)
    {
         
        // Comparing i th character
        // from starting and len-i
        // th character from end
        if (str[i] != str[len - i - 1])
            return false;
    }
 
    // If the above loop doesn't return then
    // it is palindrome
    return true;
}
 
// Driver Code
public static void Main()
{
     
    // Taking number as string
    string st = "112233445566778899000000998877665544332211";
 
    if (checkPalindrome(st) == true)
        Console.Write("Yes");
    else
        Console.Write("No");
}
}
 
// This code is contributed by subhammahato348

Java脚本


输出
Yes