Python | Check if binary representation is palindrome

Python Methods and Functions

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 a solution to this problem, please refer to bin (num) .

  • Now flip the string of the binary representation of the number and compare it with the original represented binary string, if both values ​​are equal, that means the binary representation of the number is a pallindrome, otherwise it is not.
  • Note: we can use a different approach checking the string — palindrome or not .

    # Function to check if binary representation is
    # pallinder number or not

     

    def binaryPallindrome (num):

     

    # convert number to binary

      binary = bin (num)

     

    # skip the first two line character

    # because bin adds & # 39; 0b & # 39; as

    # binary prefix

    #number

    binary = binary [ 2 :]

     

    # now flip the binary string and compare

    # this is with the original

    return binary = = binary [ - 1 :: - 1 ]

     
    # Driver program

    if __ name__ = = "__ main__" :

    num = 9

    print binaryPallindrome (num)

    Output:

     True 




  • Tutorials