Home » Python » Python programs

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?
Submitted by Bipin Kumar, on November 21, 2019

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.

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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.