1、逐位
uint32_t reverseBits(uint32_t n) {
int count = 32;
uint32_t ans = 0;
while (n) {
count--;
ans = ans << 1;
if (n % 2 == 1) {
ans += 1;
}
n /= 2;
}
while (count) {
ans = ans << 1;
count--;
}
return ans;
}
时间:O(n) 空间:O(1)
2、位运算分治
const uint32_t h1 = 0x55555555;
const uint32_t h2 = 0x03030303;
const uint32_t h3 = 0x0f0f0f0f;
const uint32_t h4 = 0x00ff00ff;
uint32_t reverseBits(uint32_t n) {
n = ((n >> 1) & h1) | ((n & h1) << 1);
n = ((n >> 2) & h2) | ((n & h2) << 2);
n = ((n >> 4) & h3) | ((n & h3) << 4);
n = ((n >> 8) & h4) | ((n & h4) << 8);
n = (n >> 16) | (n << 16);
return n;
}
时间:O(1) 空间:O(1)
方法二参考力扣官方题解