Q:

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

belongs to collection: Python basic programs

0

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.

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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.

Program:

# 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

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Draw a pie chart that shows our daily activity in ... >>
<< Check whether a number is a power of another numbe...