Check if Binary representation is Palindrome in Python (original) (raw)

Last Updated : 29 Oct, 2025

Given a number n, the task is to check whether its binary representation is a palindrome or not. A binary palindrome means that the binary digits of a number read the same backward as forward.

**For Example:

**Input: n = 9 -> **Binary: 1001 -> **Output: True
**Input: n = 10 -> **Binary: 1010 -> **Output: False

Let’s explore different ways to check this in Python.

Using Bitwise Operations (Without String Conversion)

This method checks palindrome property purely with bit manipulation. It extracts bits from both ends using shifting and masking. Avoids any string operation.

Python `

n = 9 bits = n.bit_length() is_palindrome = True

for i in range(bits // 2): if ((n >> i) & 1) != ((n >> (bits - i - 1)) & 1): is_palindrome = False break

print(is_palindrome)

`

**Explanation:

Using String Reversal

This method converts the number into its binary form, removes the '0b' prefix, and checks if the binary string is the same when reversed. It’s short, efficient, and uses Python’s built-in slicing.

Python `

n = 9 b = bin(n)[2:]
print(b == b[::-1])

`

**Explanation:

Using Iteration (Two-pointer Approach)

Instead of reversing the string, this method compares characters from both ends moving toward the center. It avoids creating an extra reversed copy, making it slightly more memory-efficient.

Python `

n = 9 b = bin(n)[2:] left, right = 0, len(b) - 1

is_palindrome = True while left < right: if b[left] != b[right]: is_palindrome = False break left += 1 right -= 1

print(is_palindrome)

`

**Explanation:

Using Manual Reverse Construction

This method builds the reverse binary manually using bit manipulation and then compares it to the original. It’s slower than the direct check but useful for understanding binary manipulation.

Python `

n = 9 original = n rev = 0 bits = n.bit_length()

for i in range(bits): rev = (rev << 1) | (n & 1) n >>= 1

print(original == rev)

`

**Explanation: