blog/content/post/算法题/位运算操作.md
2025-09-06 01:47:38 +08:00

42 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 位运算常用操作归纳
description: 位运算常用操作归纳
date: 2025-09-06T01:37:00+08:00
lastmod: 2025-09-06T01:37:00+08:00
slug: 位运算操作
# image: helena-hertz-wWZzXlDpMog-unsplash.jpg
categories:
- 算法题
tags: [
"位运算",
"动态规划"
]
math: true
---
下面的第k位是从0开始计数的。
| 位运算 | 解释 |
| ---------------------- | --------------------------------- |
| `lowbit(i)``i & -i` | 返回`i`的最后一位1以及后面的0 |
| `(n >> k) & 1` | 求n的第k位数字 |
| `x \| (1 << k)` | 将x第k位置为1 |
| `x & ~(1 << k)` | 将x第k位置为0 |
| `x ^ (1 << k)` | 将x第k位取反 |
| `x & (x - 1)` | 将x最右边的1置为0 (去掉最右边的1) |
| `x \| (x + 1)` | 将x最右边的0置为1 |
| `x & 1` | 判断奇偶性:真为奇,假为偶 |
| `(n > 0) && ((n & (n - 1)) == 0)` | 判断n是否为2的幂。因为2的幂的二进制只有一个1用n & (n-1)可以直接把它唯一的1去掉变成0。
| `n & ((1 << k) - 1)` | 等价于 `n % (1 << k)`,即`n`对$2^k$取模 |
统计二进制数中1的个数
```cpp
int countOnes(int n) {
int count = 0;
while (n) {
n &= (n - 1); // 即 n = n & (n - 1)
count++;
}
return count;
}
```