classSolution:defreverseBits(self, n:int)->int:
binary =list(bin(n))
binary.pop(0)
binary.pop(0)# 去除前缀for i inrange(32-len(binary)):# 将转换过程中缺失的0补齐
binary.insert(0,'0')
binary = binary[::-1]# 倒置
binary ="".join(binary)# 形成字符串
res =0for i inrange(len(binary)):# 还原成数字
res = res*2+int(binary[i])return res
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
3.官方的解决方案
classSolution:defreverseBits(self, n:int)->int:# 采用简单的位运算就可以完成# 瞬间感觉写出的是没有智商的人写出的东西
res =0for i inrange(32):
res =(res<<1)+(n&1)# 注意,移位是1不是2
n >>=1return res
classSolution:defreverseBits(self, n:int)->int:# 使用分治法# 位运算的操作秀到我"""
1.抽取
2.移位
3.相或
"""# 间隔一位抽取
xaaaaaaaa =10101010101010101010101010101010
x55555555 =01010101010101010101010101010101# 间隔两位抽取
xcccccccc =11001100110011001100110011001100
x33333333 =00110011001100110011001100110011# 间隔四位抽取
xf0f0f0f0 =11110000111100001111000011110000
x0f0f0f0f =00001111000011110000111100001111# 间隔八位抽取
xff00ff00 =11111111000000001111111100000000
x00ff00ff =00000000111111110000000011111111
n =((n&xaaaaaaaa)>>1)|((n&x55555555)<<1)
n =((n&xcccccccc)>>2)|((n&x33333333)<<2)
n =((n&xf0f0f0f0)>>4)|((n&x0f0f0f0f)<<4)
n =((n&xff00ff00)>>8)|((n&x00ff00ff)<<8)return n>>16| n <<16
运行成功的代码
classSolution:defreverseBits(self, n:int)->int:# 使用分治法# 位运算的操作秀到我"""
1.抽取
2.移位
3.相或
"""
n =((n&0xaaaaaaaa)>>1)|((n&0x55555555)<<1)
n =((n&0xcccccccc)>>2)|((n&0x33333333)<<2)
n =((n&0xf0f0f0f0)>>4)|((n&0x0f0f0f0f)<<4)
n =((n&0xff00ff00)>>8)|((n&0x00ff00ff)<<8)
n =((n&0xffff0000)>>16)|((n&0x0000ffff)<<16)return n