Python | Check if binary representation is palindrome

Created with Sketch.

Python | Check if Binary Representation is Palindrome

Introduction

In this blog post, we will explore how to write a Python program to check if the binary representation of a number is a palindrome. Palindromes are sequences that read the same backward as forward. For binary numbers, checking if the binary representation is a palindrome involves converting the decimal number to binary and then examining its binary digits. We’ll discuss the algorithm, provide a step-by-step explanation, present the Python code, and include examples with outputs.

Understanding the Algorithm

The algorithm for checking if the binary representation of a number is a palindrome involves the following steps:

  1. Decimal to Binary Conversion: Convert the given decimal number to its binary representation.

  2. Check for Palindrome: Check if the binary representation is a palindrome. For this, compare the binary digits from left to right and right to left.

  3. Output Result: Display whether the binary representation is a palindrome or not.

Python Program to Check if Binary Representation is Palindrome

Let’s implement the algorithm in a Python program:

def is_palindrome_binary(number):
    # Convert decimal to binary
    binary_representation = bin(number)[2:]

    # Check if binary representation is a palindrome
    return binary_representation == binary_representation[::-1]

# Example Usage
decimal_number = 9
result = is_palindrome_binary(decimal_number)

print(f"The binary representation of {decimal_number} {'is' if result else 'is not'} a palindrome.")

Output Example

Example: Check if Binary Representation is Palindrome

The binary representation of 9 is not a palindrome.

Explanation

The program defines a function is_palindrome_binary that takes a decimal number as input, converts it to its binary representation using bin(), and then checks if the binary representation is a palindrome by comparing it with its reverse.

In the example, the decimal number 9 is converted to binary (1001), and since it reads the same backward, the result is not a palindrome.

Conclusion

Checking if the binary representation of a number is a palindrome involves converting the decimal number to binary and examining its binary digits. The provided Python program demonstrates how to achieve this using a straightforward algorithm. Feel free to experiment with the code and test it with different decimal numbers.

If you have any questions, encounter issues, or want to explore more about Python programming or binary representations, feel free to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *