I love Python! It has such a lot of cool features with string manipulation, such as slicing.
def reverseBits(self, n): return int(bin(n)[2:].zfill(32)[::-1], 2)
Runtime is 52ms. Slower than most solutions posted here though. I'm just trying to get my hands dirty on Python :)
My Solution is similar to yours
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): str_bin = bin(n)[2:] if len(str_bin) < 32: str_bin = (32-len(str_bin))*'0' + str_bin return int('0b'+str_bin[::-1], 2)
hmm.... mine which I solved 2 years ago as well has runtime 59ms
take a look:
def reverseBits(self, n): return int(('%0*d' % (32, int(bin(n)[2:])))[::-1], 2)
@woodrat sorry, may I know why the slice of bin starts from 2?
str_bin = bin(n)[2:]
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.