问题描述:
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
分析:这道题主要考察对bit位的操作。这里使用两个指针,从两端向中间逼近,每次交换对应项位置。
代码如下:4ms
uint32_t reverseBits(uint32_t n) {
uint32_t slow = 1 << 0, fast = 1 << 31;
while (fast>slow) {
//swap
uint32_t slowVal = slow & n;
uint32_t fastVal = fast & n;
if (slowVal) {
n |= fast;
}
else {
n &= ~fast;
}
if (fastVal) {
n |= slow;
}
else {
n &= ~slow;
}
fast = fast >> 1;
slow = slow << 1;
}
return n;
}