题目英文描述:
Reverse bits of a given 32 bits unsigned integer.
题目中文描述:
颠倒给定的 32 位无符号整数的二进制位。
代码(利用位运算逐位颠倒):
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0, end = 31;
while(n != 0) { //n = 0时代表输入前面位数都为0,输出不用操作即可补零,可提前退出循环
result += (n & 1) << end--;
n >>= 1;
}
return result;
}
};
代码(分治):
思路:首先,将原来的32位分为2个16位的块,然后我们将16位块分成2个8位的块,然后我们继续将这些块分成更小的块,直到达到1位的块,在上述每个步骤中,我们将中间结果合并为一个整数,作为下一步的输入。
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n >> 16) | (n << 16);
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
return n;
}
};