Check whether the binary representation of a given number is a palindrome or not in Python

Here, we will learn how to check the binary representation of a given number is a palindrome or not in Python programming language? By Bipin Kumar Last updated : January 05, 2024

A positive number or string is said to be a palindrome if the reverse of the number or string is equal to the given number or string. For example, 132231 is a palindrome but 13243 is not.

Problem statement

In this problem, a number will be given by the user and we have to convert it into a binary number and after this, we will check the binary representation is a palindrome or not.

Before going to do the given task, we will learn how to convert a number into a binary number.

Python program to convert a given decimal number (P) to binary number

# input the number
P = int(input("Enter a number: "))

# convert into binary number
s = int(bin(P)[2:])

# printing the result
print("The binary representation of number:", s)

Output

The output of the above example is:

RUN 1:
Enter a number: 17
The binary representation of number: 10001

RUN 2:
Enter a number: 100
The binary representation of number: 1100100

As we have learned how to convert a decimal number into a binary number in the above program and the binary representation of 90 is not a palindrome and this is our main task to check palindrome using Python. Now, we can easily solve it. So, let’s start writing the program to check the binary representation of the given number is a palindrome or not in Python.

Python program to check whether the binary representation of a given number is a palindrome or not

# input the number
P = int(input("Enter a number: "))

# converting to binary
s = int(bin(P)[2:])

# reversing the binary
r = str(s)[::-1]

# checking the palindrome
if int(r) == s:
    print("The binary representation of the number is a palindrome.")
else:
    print("The binary representation of the number is not a palindrome.")

Output

The output of the above example is:

RUN 1:
Enter a number: 27
The binary representation of the number is a palindrome.

RUN 2:
Enter a number: 100
The binary representation of the number is not a palindrome.

In Python, str(P)[::-1] is used to reverse a number P which is a property of slicing.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.