Check if Binary representation is Palindrome in Python - GeeksforGeeks (2024)

Last Updated : 14 Mar, 2023

Summarize

Comments

Improve

Given an integer ‘n’, write a Python function that returns true if binary representation of x is palindrome else return false. Examples:

Input : n = 9Output : TrueBinary representation of n=9 is 1001 which is palindrome as well.Input : n = 10Output : FalseBinary 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.

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.



Please Login to comment...

Check if Binary representation is Palindrome in Python - GeeksforGeeks (2024)
Top Articles
Is UserTesting Legit Or A Scam? (Honest Review & Earnings!)
Docusign Support Center
Pollen Count Centreville Va
Cranes For Sale in United States| IronPlanet
NYT Mini Crossword today: puzzle answers for Tuesday, September 17 | Digital Trends
Www.1Tamilmv.cafe
Bj 사슴이 분수
T Mobile Rival Crossword Clue
Insidious 5 Showtimes Near Cinemark Tinseltown 290 And Xd
How Much Is 10000 Nickels
Alpha Kenny Buddy - Songs, Events and Music Stats | Viberate.com
Khatrimaza Movies
Here's how eating according to your blood type could help you keep healthy
Weapons Storehouse Nyt Crossword
Max 80 Orl
Beau John Maloney Houston Tx
180 Best Persuasive Essay Topics Ideas For Students in 2024
Munich residents spend the most online for food
Michael Shaara Books In Order - Books In Order
Craigslist Free Stuff Merced Ca
Sni 35 Wiring Diagram
Outlet For The Thames Crossword
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
A Christmas Horse - Alison Senxation
2023 Ford Bronco Raptor for sale - Dallas, TX - craigslist
208000 Yen To Usd
My Reading Manga Gay
Our 10 Best Selfcleaningcatlitterbox in the US - September 2024
How To Improve Your Pilates C-Curve
Used Safari Condo Alto R1723 For Sale
Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Brenda Song Wikifeet
Bratislava | Location, Map, History, Culture, & Facts
Here’s how you can get a foot detox at home!
Usf Football Wiki
Dogs Craiglist
Updates on removal of DePaul encampment | Press Releases | News | Newsroom
'Guys, you're just gonna have to deal with it': Ja Rule on women dominating modern rap, the lyrics he's 'ashamed' of, Ashanti, and his long-awaited comeback
Hkx File Compatibility Check Skyrim/Sse
Stosh's Kolaches Photos
Reilly Auto Parts Store Hours
Maplestar Kemono
Yosemite Sam Hood Ornament
Dineren en overnachten in Boutique Hotel The Church in Arnhem - Priya Loves Food & Travel
Upcoming Live Online Auctions - Online Hunting Auctions
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Craigslist.raleigh
Bob Wright Yukon Accident
Leslie's Pool Supply Redding California
What Responsibilities Are Listed In Duties 2 3 And 4
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 5595

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.