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?
Related problem: Reverse Integer
自己开始想的方法是暴力,开一个vector把n%2的每一位存在vector里,正好是反过来的顺序,然后把vector里的0和1转成整数形式然后看别人的题解,可以用位运算,用n&1判断n的当前位是否为1,如果n&1 == 1则当前位为1,否则为0. 然后用n >> 1代替 n/2,value<< 1并设置最后一位,就可以直接得出value的值。
代码如下:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t value = 0;
if (n == 0) return value;
for (int i = 0; i < 32; i++) {
value = value << 1;
if (n&1 == 1)
value++; // 设置最后一位为1
n = n >> 1;
}
return value;
}
};