给定一个数字N,其中包含偶数个数字。任务是检查该数字是否为回文。
例子:
Input: N = 123321
Output: Palindrome
Input: 1234
Output: Not palindrome
天真的方法是从该数字的前后移动,并在不匹配的地方停止。
一种有效的方法是使用以下事实:
Palindrome Number having even number of digits is always divisible by 11.
假设数字是d1 d2 d3 d4…dn ,其中d1,d2,d3 ..是数字的数字。如果是回文,则d1 = dn,d2 = dn-1,d3 = dn-2…..依此类推。现在,由于11的可除性指出,数字的备用数字总和之差应为零,而回文数甚至为零的情况也应相同。的数字即
d1 + d3 + …+ dn-1 = d2 + d4 + d6 + … + dn
因此,具有偶数位数的回文数始终可以被11整除。
C++
// C++ program to find number is palindrome
// or not without using any extra space
#include
using namespace std;
// Function to check if the number is palindrome
bool isPalindrome(int n)
{
// if divisible by 11 then true
if (n % 11 == 0) {
return true;
}
// if not divisible by 11
return false;
}
// Driver code
int main()
{
isPalindrome(123321) ? cout << "Palindrome"
: cout << "Not Palindrome";
return 0;
}
Java
// Java program to find number
// is palindrome or not without
// using any extra space
class GFG
{
// Function to check if the
// number is palindrome
static boolean isPalindrome(int n)
{
// if divisible by 11 then true
if (n % 11 == 0)
{
return true;
}
// if not divisible by 11
return false;
}
// Driver code
public static void main(String[] args)
{
System.out.println(isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome");
}
}
// This code is contributed by Bilal
Python3
# Python 3 program to find number is palindrome
# or not without using any extra space.
# Function to check if the number is palindrome
def isPalindrome(n) :
# if divisible by 11 then return True
if n % 11 == 0 :
return True
# if not divisible by 11 then return False
return False
# Driver code
if __name__ == "__main__" :
n = 123321
if isPalindrome(n) :
print("Palindrome")
else :
print("Not Palindrome")
# This code is contributed by ANKITRAI1
C#
// C# program to find number
// is palindrome or not without
// using any extra space
using System;
class GFG
{
// Function to check if the
// number is palindrome
static bool isPalindrome(int n)
{
// if divisible by
// 11 then true
if (n % 11 == 0)
{
return true;
}
// if not divisible by 11
return false;
}
// Driver code
public static void Main()
{
Console.Write(isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome");
}
}
// This code is contributed
// by ChitraNayal
PHP
Javascript
输出:
Palindrome