位运算


二进制表示中最低位

231. 2 的幂

1
n & (n - 1)

上式表示将 n 二进制表示的最低位 1 移除

如果如果n是正整数并且 n & (n - 1) = 0,那么 n 就是 2 的幂。

1
n & (-n)

如果n是正整数并且 n & (-n) = n,那么 n 就是 2 的幂。

作者:力扣官方题解
链接:https://leetcode.cn/problems/power-of-two/solutions/796201/2de-mi-by-leetcode-solution-rny3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

190. 颠倒二进制位

位运算分治

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
private:
const uint32_t M1 = 0x55555555; // 01010101010101010101010101010101
const uint32_t M2 = 0x33333333; // 00110011001100110011001100110011
const uint32_t M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
const uint32_t M8 = 0x00ff00ff; // 00000000111111110000000011111111

public:
uint32_t reverseBits(uint32_t 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;
}
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/reverse-bits/solutions/685436/dian-dao-er-jin-zhi-wei-by-leetcode-solu-yhxz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Brian Kernighan算法

用于清除二进制数中最右侧的1

1
x = x & (x - 1)

一比特数

计算二进制表示中的 1 的数目

1
2
3
4
5
6
7
8
int countOnes(int x) {
int ones = 0;
while (x > 0) {
x &= (x - 1);
ones++;
}
return ones;
}