Open In App

Check if Binary representation is Palindrome in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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,

  1. Convert given number into it’s binary representation using bin(num) function.
  2. 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.
  3.  

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)


Output

True

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))


Output

True

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.



Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads