Python Program to Check if Binary Representation Is a Palindrome

1. Introduction

In computer science, palindromes are not just confined to textual strings but can also extend to binary representations of numbers. A binary palindrome is a binary number that reads the same forward and backward. Checking for this property involves examining the binary representation of a number.

2. Problem

Develop a Python program that determines whether the binary representation of a given integer is a palindrome.

3. Solution Steps

1. Convert the given integer to its binary representation.

2. Strip the '0b' prefix that Python uses to indicate a binary number.

3. Check if the binary string is a palindrome.

4. Return and print the result.

4. Code Program

# Function to check if the binary representation of a number is a palindrome
def is_binary_palindrome(num):
    # Convert number to binary and remove the '0b' prefix
    binary_str = bin(num)[2:]
    # Check if the binary string is a palindrome
    return binary_str == binary_str[::-1]

# Given number
number = 9

# Check if its binary representation is a palindrome
binary_palindrome = is_binary_palindrome(number)

# Print the result
print(f"Is the binary representation of {number} a palindrome? {binary_palindrome}")

Output:

Is the binary representation of 9 a palindrome? True

Explanation:

1. The function is_binary_palindrome converts the given num to a binary string using bin(num) and removes the '0b' prefix with slicing [2:].

2. It then checks whether this binary string is the same as its reverse.

3. For the number 9, whose binary representation is 1001, the function returns True since 1001 is a palindrome.

4. The print statement outputs the final result, indicating the binary representation of the number 9 is indeed a palindrome.

Comments