Grand 169 questions 第4周
第1题-190. 颠倒二进制位
暴力
很容易想到,我们可以计算出n的最低位,然后将其左移32 - i - 1位。
这样,就颠倒了n的最低位,依次顺序,知道n == 0即可。
public class Solution {
public uint reverseBits(uint n) {
uint ret = 0;
for (int i = 0; i < 32 && n > 0; ++i) {
ret |= (n & 1) << (31 - i);
n >>= 1;
}
return ret;
}
}
分治位运算
笑死,根本想不到,我是废物
这个是源码级的算法。
public class Solution {
private static uint M1 = 0x55555555; // 01010101010101010101010101010101
private static uint M2 = 0x33333333; // 00110011001100110011001100110011
private static uint M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
private static uint M8 = 0x00ff00ff; // 00000000111111110000000011111111
public uint reverseBits(uint n) {
n = n >> 1 & M1 | (n & M1) << 1;
n = n >> 2 & M2 | (n & M2) << 2;
n = n >> 4 & M4 | (n & M4) << 4;
n = n >> 8 & M8 | (n & M8) << 8;
return n >> 16 | n << 16;
}
}