Problem Definition:
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
return 964176192 (represented in binary as 00111001011110000010100101000000).
Solution : (很 Python)
1 def reverseBits(n): 2 return int(((bin(n)[2:]).rjust(32,'0')[::-1]),2)
It can be expanded to:
1 def reverseBits(self,n): 2 s=bin(n)[2:] 3 s=s.rjust(32,'0') 4 s=s[::-1] 5 return int(s,2)
然而这题真正的考点在于位运算
这里可以采用一种类似归并排序的思想(且称之为归并取反吧)
1 def reverseBits(self,n): 2 n=((n & 0xAAAAAAAA)>>1)|((n & 0x55555555)<<1) 3 n=((n & 0xCCCCCCCC)>>2)|((n & 0x33333333)<<2) 4 n=((n & 0xF0F0F0F0)>>4)|((n & 0x0F0F0F0F)<<4) 5 n=((n & 0xFF00FF00)>>8)|((n & 0x00FF00FF)<<8) 6 n=((n & 0xFFFF0000)>>16)|((n & 0x0000FFFF)<<16) 7 return n