Check if a number with even number of digits is palindrome or not
Last Updated :
31 Jul, 2022
Given a number N containing an even number of digits . The task is to check whether that number is palindrome or not.
Examples:
Input: N = 123321
Output: Palindrome
Input: 1234
Output: Not palindrome
A Naive Approach is to traverse from the front and back of that number and stop where they do not match. An Efficient Approach is to use the below fact:
Palindrome Number having even number of digits is always divisible by 11.
Suppose the number is d1 d2 d3 d4…dn , whered1, d2, d3.. are digits of a number. If it is a palindrome then d1 = dn, d2 = dn-1, d3 = dn-2…..and so on. Now since divisibility of 11 states that the difference of sum of alternate digits of a number should be zero and same in the case of palindrome having even no. of digits i.e.
d1 + d3 + …+ dn-1 = d2 + d4 + d6 + … + dn
So, a palindromic number having even number of digits is always divisible by 11.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPalindrome(int n)
{
if (n % 11 == 0) {
return true;
}
return false;
}
int main()
{
isPalindrome(123321) ? cout << "Palindrome"
: cout << "Not Palindrome";
return 0;
}
Java
class GFG
{
static boolean isPalindrome(int n)
{
if (n % 11 == 0)
{
return true;
}
return false;
}
public static void main(String[] args)
{
System.out.println(isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome");
}
}
Python3
def isPalindrome(n) :
if n % 11 == 0 :
return True
return False
if __name__ == "__main__" :
n = 123321
if isPalindrome(n) :
print("Palindrome")
else :
print("Not Palindrome")
C#
using System;
class GFG
{
static bool isPalindrome(int n)
{
if (n % 11 == 0)
{
return true;
}
return false;
}
public static void Main()
{
Console.Write(isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome");
}
}
PHP
<?php
function isPalindrome($n)
{
if ($n % 11 == 0)
{
return true;
}
return false;
}
echo isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome";
?>
Javascript
<script>
function isPalindrome(n)
{
if (n % 11 == 0)
{
return true;
}
return false;
}
document.write(isPalindrome(123321) ?
"Palindrome" :
"Not Palindrome");
</script>
Time Complexity: O(1)Auxiliary Space: O(1)
Share your thoughts in the comments
Add Your Comment
Please Login to comment...