check if binary number is palindrome in python

To check if a binary number is palindrome, we can first convert it to a string and then check if the string is equal to its reverse. Here's the Python code to do that using loops:

main.py
def is_binary_palindrome(n):
    binary_str = bin(n)[2:]  # convert to binary string, ignore '0b' prefix
    # check if binary string is equal to its reverse
    for i in range(len(binary_str)//2):
        if binary_str[i] != binary_str[-i-1]:
            return False
    return True
285 chars
8 lines

Some key points to note:

  • We use the built-in bin() function to convert the input number n to a binary string.
  • The // operator performs integer division, which ensures that we get the correct midpoint index in case the length of the binary string is odd.
  • The loop compares the first half of the binary string with the corresponding elements in the second half (in reverse order), and returns False as soon as a mismatch is found.
  • If the loop completes without finding a mismatch, the binary number is a palindrome and we return True.

gistlibby LogSnag