解法1:逐位颠倒。swap(0, 31), swap(1, 30) ... swap(15, 16)
解法2:利用掩码先互换奇偶bit位,再互换奇偶2 bits,再互奇偶4 bits (half byte),再互换奇偶byte,最后互换奇偶16 bits 注意:解法2种python直接翻译的C++,C++能过,而Python却不能,如有Python大神指导原因,麻烦留言告知,先行谢过!
class Solution1 {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t res = 0;
int INT_LEN = 32;
for (int i = 0; i < INT_LEN; i++) {
res |= (n & 0x1) << (INT_LEN - i - 1);
n >>= 1;
}
return res;
}
};
class Solution {
private:
const uint32_t M1 = 0x55555555; // 01010101010101010101010101010101
const uint32_t M2 = 0x33333333; // 00110011001100110011001100110011
const uint32_t M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
const uint32_t M8 = 0x00ff00ff; // 00000000111111110000000011111111
public:
uint32_t reverseBits(uint32_t n) {
n = n >> 1 & M1 | (n & M1) << 1;
n = n >> 2 & M2 | (n & M2) << 2;
n = n >> 4 & M4 | (n & M4) << 4;
n = n >> 8 & M8 | (n & M8) << 8;
return n >> 16 | n << 16;
}
};
class Solution1:
def reverseBits(self, n: int) -> int:
res = 0
INT_LEN = 32
for i in range(0, INT_LEN) :
res |= (n & 0x1) << (INT_LEN - i - 1)
n >>= 1
return res
class Solution:
def reverseBits(self, n) :
M1 = 0x55555555 # 01010101010101010101010101010101
M2 = 0x33333333 # 00110011001100110011001100110011
M4 = 0x0f0f0f0f # 00001111000011110000111100001111
M8 = 0x00ff00ff # 00000000111111110000000011111111
n = ((n >> 1) & M1) | ((n & M1) << 1)
n = ((n >> 2) & M2) | ((n & M2) << 2)
n = ((n >> 4) & M4) | ((n & M4) << 4)
n = ((n >> 8) & M8) | ((n & M8) << 8)
return (n >> 16) | (n << 16)