Python | Check if binary representation is palindrome

Given an integer ‘n’, write a Python function that returns true if binary representation of x is palindrome else return false.

Examples:

Input : n = 9
Output : True
Binary representation of n=9 is 1001 which 
is palindrome as well.

Input : n = 10
Output : False
Binary representation of n=10 is 1010 which 
is not palindrome.



We have existing solution for this problem please refer Check if binary representation of a number is palindrome link. We can solve this problem in python very quickly. Approach is very simple,

  1. Convert given number into it’s binary representation using bin(num) function.
  2. Now reverse binary representation string of number and compare it with original binary represented string, if both are equal that means binary representation of number is pallindrome else not.

Note : We can use other approach of checking a string is palindrome or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to check if binary representation of
# a number is pallindrome or not
  
def binaryPallindrome(num):
  
     # convert number into binary
     binary = bin(num)
  
     # skip first two characters of string
     # because bin function appends '0b' as 
     # prefix in binary representation of
     # a number
     binary = binary[2:]
  
     # now reverse binary string and compare
     # it with original
     return binary == binary[-1::-1]
  
# Driver program
if __name__ == "__main__":
    num = 9
    print binaryPallindrome(num)

chevron_right


Output:

True


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.