Check if binary representation of a number is palindrome in python; In this python article, we would love to share with you how to check the binary representation of a given number is a palindrome or not in Python?
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, 141 is a palindrome but 142 is not.
Before going to do the write a program to check whether the binary equivalent of a given number is a palindrome in python, you should learn how to convert a number into a binary number.
Here, you will learn how to convert a given decimal number to binary number by using the given-below python program.
Python program to convert a given decimal number to binary number
# Python program to convert a given decimal number to binary number # take input the number from user x=int(input('Enter a number: ')) # convert into binary number y=int(bin(x)[2:]) # display the result print("The binary representation of number:", y)
Output
Enter a number: 17 The binary representation of number: 10001
Python Program to Check Whether the Binary Equivalent of a Given Number is Palindrome
- Take the input number from user by using input() function.
- Convert number into a binary number.
- After this, we will check the binary representation is a palindrome or not.
- Print result.
# Python Program to Check Whether the Binary Equivalent of a Given Number is Palindrome # take input the number user x=int(input('Enter a number: ')) # converting to binary y=int(bin(x)[2:]) # reversing the binary out=str(y)[::-1] print("The binary representation of number:", y) # checking the palindrome if int(out)==y: print("The binary representation of the number is a palindrome.") else: print("The binary representation of the number is not a palindrome.")
Output
Enter a number: 17 The binary representation of number: 10001 The binary representation of the number is a palindrome.