Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Solution: Bit Manipulation.
Running Time: O(n)
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
for i in range(32):
if n & 1 == 1:
result = (result << 1) + 1
else:
result <<= 1
n >>= 1
return result
优化方法: 以4位为单位执行反转,将0x0至0xF的反转结果预存在一个长度为16的数组中,反转时直接查询。
https://leetcode.com/discuss/27338/8ms-c-code-some-ideas-about-optimization-spoiler