0%

190. 颠倒二进制位

190. 颠倒二进制位

题目意思讲的有点不清楚,题意是:

把给定的二进制串左右颠倒,即111001 -> 100111

不得不说,whca

直接循环32次,然后把位倒着放。

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int ret = 0;
for(int i = 0; i < 32; ++i)
{
ret |= (n & 1) << (31 - i);
n >>= 1;
}
return ret;
}
};
DQ

颠倒2位->颠倒4位->颠倒8位->颠倒16位->颠倒32位 自底而上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
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);
}
private:
uint32_t M1 = 0x55555555;
uint32_t M2 = 0x33333333;
uint32_t M3 = 0x0f0f0f0f;
uint32_t M4 = 0x00ff00ff;
};