常用的位操作.md 11.9 KB
Newer Older
L
labuladong 已提交
1 2
# 常用的位运算技巧

3 4
<p align='center'>
<a href="https://github.com/labuladong/fucking-algorithm" target="view_window"><img alt="GitHub" src="https://img.shields.io/github/stars/labuladong/fucking-algorithm?label=Stars&style=flat-square&logo=GitHub"></a>
L
labuladong 已提交
5
<a href="https://appktavsiei5995.pc.xiaoe-tech.com/index" target="_blank"><img class="my_header_icon" src="https://img.shields.io/static/v1?label=精品课程&message=查看&color=pink&style=flat"></a>
6 7 8 9
<a href="https://www.zhihu.com/people/labuladong"><img src="https://img.shields.io/badge/%E7%9F%A5%E4%B9%8E-@labuladong-000000.svg?style=flat-square&logo=Zhihu"></a>
<a href="https://space.bilibili.com/14089380"><img src="https://img.shields.io/badge/B站-@labuladong-000000.svg?style=flat-square&logo=Bilibili"></a>
</p>

L
labuladong 已提交
10
![](https://labuladong.github.io/algo/images/souyisou1.png)
11

L
labuladong 已提交
12
**通知:[数据结构精品课](https://aep.h5.xeknow.com/s/1XJHEO) 已更新到 V2.0;[第 13 期刷题打卡](https://mp.weixin.qq.com/s/eUG2OOzY3k_ZTz-CFvtv5Q) 最后一天报名!另外,建议你在我的 [网站](https://labuladong.github.io/algo/) 学习文章,体验更好。**
13 14 15



L
labuladong 已提交
16 17 18 19 20 21 22 23 24
读完本文,你不仅学会了算法套路,还可以顺便解决如下题目:

| LeetCode | 力扣 | 难度 |
| :----: | :----: | :----: |
| [136. Single Number](https://leetcode.com/problems/single-number/) | [136. 只出现一次的数字](https://leetcode.cn/problems/single-number/) | 🟢
| [191. Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/) | [191. 位1的个数](https://leetcode.cn/problems/number-of-1-bits/) | 🟢
| [231. Power of Two](https://leetcode.com/problems/power-of-two/) | [231. 2 的幂](https://leetcode.cn/problems/power-of-two/) | 🟢
| [268. Missing Number](https://leetcode.com/problems/missing-number/) | [268. 丢失的数字](https://leetcode.cn/problems/missing-number/) | 🟢
| - | [剑指 Offer 15. 二进制中1的个数](https://leetcode.cn/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/) | 🟢
25 26 27

**-----------**

L
labuladong 已提交
28
本文分两部分,第一部分列举几个有趣的位操作,第二部分讲解算法题中常用的位运算操作。因为位操作很简单,所以假设读者已经了解与、或、异或这三种基本操作。
L
labuladong 已提交
29 30 31 32 33

位操作(Bit Manipulation)可以玩出很多奇技淫巧,但是这些技巧大部分都过于晦涩,没必要深究,读者只要记住一些有用的操作即可。

### 一、几个有趣的位操作

34
1. **利用或操作 `|` 和空格将英文字符转换为小写**
L
labuladong 已提交
35

L
labuladong 已提交
36
```java
L
labuladong 已提交
37 38 39 40
('a' | ' ') = 'a'
('A' | ' ') = 'a'
```

41
2. **利用与操作 `&` 和下划线将英文字符转换为大写**
L
labuladong 已提交
42

L
labuladong 已提交
43
```java
L
labuladong 已提交
44 45 46 47
('b' & '_') = 'B'
('B' & '_') = 'B'
```

48
3. **利用异或操作 `^` 和空格进行英文字符大小写互换**
L
labuladong 已提交
49

L
labuladong 已提交
50
```java
L
labuladong 已提交
51 52 53 54
('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd'
```

L
labuladong 已提交
55
以上操作能够产生奇特效果的原因在于 ASCII 编码。ASCII 字符其实就是数字,恰巧这些字符对应的数字通过位运算就能得到正确的结果,有兴趣的读者可以查 ASCII 码表自己算算,本文就不展开讲了。
L
labuladong 已提交
56

57
4. **判断两个数是否异号**
L
labuladong 已提交
58

L
labuladong 已提交
59
```java
L
labuladong 已提交
60
int x = -1, y = 2;
L
labuladong 已提交
61
boolean f = ((x ^ y) < 0); // true
L
labuladong 已提交
62 63

int x = 3, y = 2;
L
labuladong 已提交
64
boolean f = ((x ^ y) < 0); // false
L
labuladong 已提交
65 66
```

67
这个技巧还是很实用的,利用的是补码编码的符号位。如果不用位运算来判断是否异号,需要使用 if else 分支,还挺麻烦的。读者可能想利用乘积或者商来判断两个数是否异号,但是这种处理方式可能造成溢出,从而出现错误。
L
labuladong 已提交
68

69
5. **不用临时变量交换两个数**
L
labuladong 已提交
70

L
labuladong 已提交
71
```java
L
labuladong 已提交
72 73 74 75 76 77 78
int a = 1, b = 2;
a ^= b;
b ^= a;
a ^= b;
// 现在 a = 2, b = 1
```

79
6. **加一**
L
labuladong 已提交
80

L
labuladong 已提交
81
```java
L
labuladong 已提交
82 83 84 85 86
int n = 1;
n = -~n;
// 现在 n = 2
```

87
7. **减一**
L
labuladong 已提交
88

L
labuladong 已提交
89
```java
L
labuladong 已提交
90 91 92 93 94
int n = 2;
n = ~-n;
// 现在 n = 1
```

L
labuladong 已提交
95
> PS:上面这三个操作就纯属装逼用的,没啥实际用处,大家了解了解乐呵一下就行。
L
labuladong 已提交
96

L
labuladong 已提交
97
### 二、`n & (n-1)` 的运用
L
labuladong 已提交
98

L
labuladong 已提交
99
**`n & (n-1)` 这个操作是算法中常见的,作用是消除数字 `n` 的二进制表示中的最后一个 1**
L
labuladong 已提交
100 101 102

看个图就很容易理解了:

L
labuladong 已提交
103
![](https://labuladong.github.io/algo/images/位操作/1.png)
104 105

其核心逻辑就是,`n - 1` 一定可以消除最后一个 1,同时把其后的 0 都变成 1,这样再和 `n` 做一次 `&` 运算,就可以仅仅把最后一个 1 变成 0 了。
L
labuladong 已提交
106

L
labuladong 已提交
107
**1、计算汉明权重(Hamming Weight)**
L
labuladong 已提交
108

L
labuladong 已提交
109
这是力扣第 191 题「位 1 的个数」:
L
labuladong 已提交
110

L
labuladong 已提交
111
![](https://labuladong.github.io/algo/images/位操作/title.png)
L
labuladong 已提交
112

L
labuladong 已提交
113 114 115 116
就是让你返回 `n` 的二进制表示中有几个 1。因为 `n & (n - 1)` 可以消除最后一个 1,所以可以用一个循环不停地消除 1 同时计数,直到 `n` 变成 0 为止。

```java
int hammingWeight(int n) {
L
labuladong 已提交
117 118 119 120 121 122 123 124 125
    int res = 0;
    while (n != 0) {
        n = n & (n - 1);
        res++;
    }
    return res;
}
```

L
labuladong 已提交
126 127 128
**2、判断一个数是不是 2 的指数**

力扣第 231 题「2 的幂」就是这个问题。
L
labuladong 已提交
129 130 131

一个数如果是 2 的指数,那么它的二进制表示一定只含有一个 1:

L
labuladong 已提交
132
```java
L
labuladong 已提交
133 134 135 136 137
2^0 = 1 = 0b0001
2^1 = 2 = 0b0010
2^2 = 4 = 0b0100
```

L
labuladong 已提交
138
如果使用  `n & (n-1)` 的技巧就很简单了(注意运算符优先级,括号不可以省略):
L
labuladong 已提交
139

L
labuladong 已提交
140 141
```java
boolean isPowerOfTwo(int n) {
L
labuladong 已提交
142 143 144 145 146
    if (n <= 0) return false;
    return (n & (n - 1)) == 0;
}
```

L
labuladong 已提交
147
### 三、`a ^ a = 0` 的运用
148

L
labuladong 已提交
149
异或运算的性质是需要我们牢记的:
150 151 152

一个数和它本身做异或运算结果为 0,即 `a ^ a = 0`;一个数和 0 做异或运算的结果为它本身,即 `a ^ 0 = a`

L
labuladong 已提交
153 154 155 156 157 158
**1、查找只出现一次的元素**

这是力扣第 136 题「只出现一次的数字」:

![](https://labuladong.github.io/algo/images/位操作/title1.png)

159 160
对于这道题目,我们只要把所有数字进行异或,成对儿的数字就会变成 0,落单的数字和 0 做异或还是它本身,所以最后异或的结果就是只出现一次的元素:

L
labuladong 已提交
161 162
```java
int singleNumber(int[] nums) {
163 164 165 166 167 168 169 170
    int res = 0;
    for (int n : nums) {
        res ^= n;
    }
    return res;
}
```

L
labuladong 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
**2、寻找缺失的元素**

这是力扣第 268 题「丢失的数字」:

![](https://labuladong.github.io/algo/images/缺失元素/title.png)

给一个长度为 `n` 的数组,其索引应该在 `[0,n)`,但是现在你要装进去 `n + 1` 个元素 `[0,n]`,那么肯定有一个元素装不下嘛,请你找出这个缺失的元素。

这道题不难的,我们应该很容易想到,把这个数组排个序,然后遍历一遍,不就很容易找到缺失的那个元素了吗?

或者说,借助数据结构的特性,用一个 HashSet 把数组里出现的数字都储存下来,再遍历 `[0,n]` 之间的数字,去 HashSet 中查询,也可以很容易查出那个缺失的元素。

排序解法的时间复杂度是 O(NlogN),HashSet 的解法时间复杂度是 O(N),但是还需要 O(N) 的空间复杂度存储 HashSet。

这个问题其实还有一个特别简单的解法:等差数列求和公式。

题目的意思可以这样理解:现在有个等差数列 `0, 1, 2,..., n`,其中少了某一个数字,请你把它找出来。那这个数字不就是 `sum(0,1,..n) - sum(nums)` 嘛?

```java
int missingNumber(int[] nums) {
    int n = nums.length;
    // 虽然题目给的数据范围不大,但严谨起见,用 long 类型防止整型溢出
    // 求和公式:(首项 + 末项) * 项数 / 2
    long expect = (0 + n) * (n + 1) / 2;
    long sum = 0;
    for (int x : nums) {
        sum += x;
    }
    return (int)(expect - sum);
}
```

不过,本文的主题是位运算,我们来讲讲如何利用位运算技巧来解决这道题。

再回顾一下异或运算的性质:一个数和它本身做异或运算结果为 0,一个数和 0 做异或运算还是它本身。

而且异或运算满足交换律和结合律,也就是说:

```java
2 ^ 3 ^ 2 = 3 ^ (2 ^ 2) = 3 ^ 0 = 3
```

而这道题索就可以通过这些性质巧妙算出缺失的那个元素,比如说 `nums = [0,3,1,4]`

![](https://labuladong.github.io/algo/images/缺失元素/1.jpg)

为了容易理解,我们假设先把索引补一位,然后让每个元素和自己相等的索引相对应:

![](https://labuladong.github.io/algo/images/缺失元素/2.jpg)

这样做了之后,就可以发现除了缺失元素之外,所有的索引和元素都组成一对儿了,现在如果把这个落单的索引 2 找出来,也就找到了缺失的那个元素。

如何找这个落单的数字呢,**只要把所有的元素和索引做异或运算,成对儿的数字都会消为 0,只有这个落单的元素会剩下**,也就达到了我们的目的:

```java
int missingNumber(int[] nums) {
    int n = nums.length;
    int res = 0;
    // 先和新补的索引异或一下
    res ^= n;
    // 和其他的元素、索引做异或
    for (int i = 0; i < n; i++)
        res ^= i ^ nums[i];
    return res;
}
```

![](https://labuladong.github.io/algo/images/缺失元素/3.jpg)

由于异或运算满足交换律和结合律,所以总是能把成对儿的数字消去,留下缺失的那个元素。
L
labuladong 已提交
241

242
以上便是一些有趣/常用的位操作。其实位操作的技巧很多,有一个叫做 Bit Twiddling Hacks 的外国网站收集了几乎所有位操作的黑科技玩法,感兴趣的读者可以查看:
L
labuladong 已提交
243

244
http://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
L
labuladong 已提交
245

L
labuladong 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274


<hr>
<details>
<summary><strong>引用本文的文章</strong></summary>

 - [丑数系列算法详解](https://labuladong.github.io/article/fname.html?fname=丑数)
 - [如何同时寻找缺失和重复的元素](https://labuladong.github.io/article/fname.html?fname=缺失和重复的元素)

</details><hr>




<hr>
<details>
<summary><strong>引用本文的题目</strong></summary>

<strong>安装 [我的 Chrome 刷题插件](https://mp.weixin.qq.com/s/X-fE9sR4BLi6T9pn7xP4pg) 点开下列题目可直接查看解题思路:</strong>

| LeetCode | 力扣 |
| :----: | :----: |
| [389. Find the Difference](https://leetcode.com/problems/find-the-difference/?show=1) | [389. 找不同](https://leetcode.cn/problems/find-the-difference/?show=1) |
| - | [剑指 Offer 15. 二进制中1的个数](https://leetcode.cn/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/?show=1) |

</details>



275
**_____________**
L
labuladong 已提交
276

L
labuladong 已提交
277
**《labuladong 的算法小抄》已经出版,关注公众号查看详情;后台回复关键词「**进群**」可加入算法群;回复「**全家桶**」可下载配套 PDF 和刷题全家桶**
L
labuladong 已提交
278 279

![](https://labuladong.github.io/algo/images/souyisou2.png)
L
labuladong 已提交
280 281


J
Jody Zhou 已提交
282 283
======其他语言代码======

B
brucecat 已提交
284 285 286 287 288 289 290 291
[191.位1的个数](https://leetcode-cn.com/problems/number-of-1-bits)

[231.2的幂](https://leetcode-cn.com/problems/power-of-two/)



### python

J
Jody Zhou 已提交
292
[JodyZ0203](https://github.com/JodyZ0203)提供 191. 位1的个数 Python3 解法代码:
J
Jody Zhou 已提交
293

J
Jody Zhou 已提交
294
```Python
J
Jody Zhou 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
class Solution:
    def hammingWeight(self, n: int) -> int:
        
        # 先定义一个count,用来存1的出现数量
        count = 0

        # 只要二进制串不等于0之前,我们用一个循环边消除1和计1的出现数量
        while n!=0:
           
            # 用labuladong在文章中所提到的 n&(n-1) 技巧来消除最后一个1
            n = n & (n-1)

            count+=1
        
        # 当二进制串全消除完之后,返回1出现的总数量
        return count
B
brucecat 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
```



### javascript

[191.位1的个数](https://leetcode-cn.com/problems/number-of-1-bits)

```js
let hammingWeight = function(n) {
    let res = 0;
    while (n !== 0) {
        n = n & (n - 1);
        res++;
    }
    return res;
}
```

[231.2的幂](https://leetcode-cn.com/problems/power-of-two/)

```js
/**
 * @param {number} n
 * @return {boolean}
 */
let isPowerOfTwo = function(n) {
    if (n <= 0) return false;
    return (n & (n - 1)) === 0;
}
```

[136. 只出现一次的数字](https://leetcode-cn.com/problems/single-number/)

查找只出现一次的元素

```js
/**
 * @param {number[]} nums
 * @return {number}
 */
let singleNumber = function(nums) {
    let res = 0;
    for (let n of nums) {
        res ^= n;
    }
    return res;
}
```