原题
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).
Follow up:
If this function is called many times, how would you optimize it?
大意就是将十进制的二进制码反转后转回十进制
先在网上找了一下 python 的进制转换问题,发现 bin(n) 可以直接将十进制转换成二进制形式,int() 可以将二进制变成十进制形式,实现反转和补成 32 位可以接受
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
b = bin(n)[:1:-1]
return int(b + '0'*(32-len(b)), 2)