添加文章
This commit is contained in:
parent
8c0dd58bed
commit
8d10c94516
41
content/post/算法题/位运算操作.md
Normal file
41
content/post/算法题/位运算操作.md
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
---
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
```
|
||||||
Loading…
x
Reference in New Issue
Block a user