法一:逐步左移相加
执行用时:44 ms, 在所有 Python3 提交中击败了52.29%的用户
内存消耗:14.6 MB, 在所有 Python3 提交中击败了85.37%的用户
class Solution:
def reverseBits(self, n: int) -> int:
res=0
for i in range(32):
res<<=1
res+=n&1
n>>=1
return res
法二:直接放高位
执行用时:44 ms, 在所有 Python3 提交中击败了52.29%的用户
内存消耗:14.9 MB, 在所有 Python3提交中击败了16.29%的用户
class Solution:
def reverseBits(self, n: int) -> int:
res=0
for i in range(32):
res|=(n&1)<<(31-i)#直接放高位
n>>=1
return res
法三:C++位运算分治法
0 ms 5.8 MB C++
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int m1=0x55555555;
int m2=0x33333333;
int m3=0x0f0f0f0f;
int m4=0x00ff00ff;
n=(n>>1&m1)|((n&m1)<<1);
n=(n>>2&m2)|((n&m2)<<2);
n=(n>>4&m3)|((n&m3)<<4);
n=(n>>8&m4)|((n&m4)<<8);
return n>>16|n<<16;
}
};
法四:python3位运算分治法
python位运算必须得有m5这一步。python不能正确运算return n>>16|n<<16
,输出46位。
45355818821952 (1010010100000000111001011110000010100101000000)
48 ms 14.8 MB Python3
class Solution:
def reverseBits(self, n: int) -> int:
'''
0x55555555==0b01010101010101010101010101010101
0x33333333==0b00110011001100110011001100110011
0x0f0f0f0f==0b00001111000011110000111100001111
0x00ff00ff==0b00000000111111110000000011111111
'''
m1=0x55555555
m2=0x33333333
m3=0x0f0f0f0f
m4=0x00ff00ff
m5=0x0000ffff
n=((n>>1)&m1)|((n&m1)<<1)
n=((n>>2)&m2)|((n&m2)<<2)
n=((n>>4)&m3)|((n&m3)<<4)
n=((n>>8)&m4)|((n&m4)<<8)
n=(n>>16)&m5|((n&m5)<<16)
return n
法五:python一行代码
return int(format(n,'032b')[::-1],2)
法六:bin()[2:]函数
[2:]是什么意思啊这里。
return int('0b'+bin(n)[2:][::-1]+'0'*(32-len(bin(n)[2:])),2)