Check if binary representation of a number is palindrome or not in Python

In this tutorial, we’re going to learn how to check if the binary representation of a number is a palindrome or not in Python. But first of all, we need to understand what’s a ‘palindrome’. If you read a number forward and backward but it still remains the same for both of the cases then we can say the number is a palindrome.

Python program: check if the binary representation of a number is Palindrome or not

def binary(n):
        no=n;
        bi="";
        if(n==0):
                bi="0";
        else:
                while(no!=1):
                        if(int(no%2)==0):
                                bi="0"+bi;
                        else:
                                bi="1"+bi;
                        no=int(no/2);
                bi="1"+bi;
        return bi;

def chk_palindrome(b):
        rev=b[::-1];
        if(rev==b):
                print("Binary representation of the no. is palindrome");
        else:
                print("Binary representation of the no. is not palindrome");

n=int(input("Please enter a no.:"));
b=binary(n);
print("The binary representation of the no. ",n," is ",b);
chk_palindrome(b);

 

Now, let us understand the program in detail:-

  1. In function ‘binary()‘, we’re finding out the binary representation of a given number.
  2. In function ‘chk_palindrome()‘, we’re checking whether the binary representation of the number is palindrome or not. Here, we created a variable ‘rev‘ where we’re storing the reverse of the binary representation. Next, we’re checking whether the binary result is palindrome or not.

 

The output of the program:

Please enter a no.:8
The binary representation of the no. 8 is 1000
Binary representation of the no. is not palindrome

Leave a Reply

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