Code (bitwise operation)
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): res = 0 for i in xrange(32): res = (res << 1) + (n & 1) n = n >> 1 return res
Idea
Use n & 1
to get the last bit. Use n >> 1
to shift n to right one bit a time. Use res << 1
to accumulate the result.
Reference: https://discuss.leetcode.com/topic/10298/the-concise-c-solution-9ms
Code (Pythonic Cheating!)
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): b = '{:032b}'.format(n) return int(b[::-1], 2)
Reference: https://discuss.leetcode.com/topic/10069/python-ac-with-63ms-3lines