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).
思路:
32位,可以遍历32次,每次用n&1,得到n最后一位bit的值val,然后就把n右移一位。用另一个值res表示要求的结果,每次与val进行一次或操作,然后左右res一位。注意res左移31位即可。
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res <<= 1;
res |= n & 1;
n >>>= 1;
}
return res;
}