Check if Binary representation is Palindrome in Python
Last Updated :
14 Mar, 2023
Given an integer ānā, write a Python function that returns true if binary representation of x is palindrome else return false. Examples:
Input : n = 9
Output : True
Binary representation of n=9 is 1001 which
is palindrome as well.
Input : n = 10
Output : False
Binary representation of n=10 is 1010 which
is not palindrome.
We have existing solution for this problem please refer Check if binary representation of a number is palindrome link. We can solve this problem in python very quickly. Approach is very simple,
- Convert given number into it's binary representation using bin(num) function.
- Now reverse binary representation string of number and compare it with original binary represented string, if both are equal that means binary representation of number is palindrome else not.
-
Note : We can use other approach of checking a string is palindrome or not.
Python
# Function to check if binary representation of
# a number is palindrome or not
def binarypalindrome(num):
# convert number into binary
binary = bin(num)
# skip first two characters of string
# because bin function appends '0b' as
# prefix in binary representation of
# a number
binary = binary[2:]
# now reverse binary string and compare
# it with original
return binary == binary[-1::-1]
# Driver program
if __name__ == "__main__":
num = 9
print binarypalindrome(num)
Using iteration:
The following is an iterative approach to the problem of checking if the binary representation of a number is a palindrome:
The first step in the function is to convert num into its binary representation using the bin function. The bin function returns a string that starts with '0b', so we use string slicing to remove these characters and just keep the binary representation.
Next, the function initializes two variables, left and right, to keep track of the indices of the left and right characters in the binary string. left is initialized to 0, while right is initialized to the length of the binary string minus 1.
The function then enters a while loop that continues as long as left is less than right. Inside the loop, the function compares the character at the left index to the character at the right index. If these characters are not equal, the function returns False immediately to indicate that the binary string is not a palindrome. If the characters are equal, the function increments left by 1 and decrements right by 1 and continues the loop.
If the loop completes, it means that all the characters in the binary string were compared and found to be equal. In this case, the function returns True to indicate that the binary string is a palindrome.
Finally, the code includes a driver program that tests the binarypalindrome function by calling it with the value 9 and printing the result.
Python3
def binarypalindrome(num):
# convert number into binary
binary = bin(num)[2:]
# initialize variables for loop
left = 0
right = len(binary) - 1
# loop through the binary string, comparing the left and right characters
while left < right:
if binary[left] != binary[right]:
return False
left += 1
right -= 1
# if the loop completes, the binary string must be a palindrome
return True
# Driver program
if __name__ == "__main__":
num = 9
print(binarypalindrome(num))
Time complexity: O(n), where n is the length of the binary string. This is because the while loop runs in linear time, with the number of iterations being equal to the length of the binary string.
Auxiliary space: O(1), as the solution only uses a constant amount of additional memory to store the variables left, right, and binary. No additional data structures are used, so the space complexity does not depend on the size of the input.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read