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

L
labuladong 已提交
3 4 5 6




7 8
<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 已提交
9
<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>
10 11 12 13
<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 已提交
14
![](https://labuladong.github.io/algo/images/souyisou1.png)
15

L
labuladong 已提交
16
**通知:[数据结构精品课](https://aep.h5.xeknow.com/s/1XJHEO) 已更新到 V1.9,点击这里体验 [刷题全家桶](https://labuladong.gitee.io/algo/images/others/%E5%85%A8%E5%AE%B6%E6%A1%B6.jpg)。**
17 18 19



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

| 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/) | 🟢
29 30 31

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

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

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

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

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

L
labuladong 已提交
40
```java
L
labuladong 已提交
41 42 43 44
('a' | ' ') = 'a'
('A' | ' ') = 'a'
```

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

L
labuladong 已提交
47
```java
L
labuladong 已提交
48 49 50 51
('b' & '_') = 'B'
('B' & '_') = 'B'
```

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

L
labuladong 已提交
54
```java
L
labuladong 已提交
55 56 57 58
('d' ^ ' ') = 'D'
('D' ^ ' ') = 'd'
```

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

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

L
labuladong 已提交
63
```java
L
labuladong 已提交
64
int x = -1, y = 2;
L
labuladong 已提交
65
boolean f = ((x ^ y) < 0); // true
L
labuladong 已提交
66 67

int x = 3, y = 2;
L
labuladong 已提交
68
boolean f = ((x ^ y) < 0); // false
L
labuladong 已提交
69 70
```

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

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

L
labuladong 已提交
75
```java
L
labuladong 已提交
76 77 78 79 80 81 82
int a = 1, b = 2;
a ^= b;
b ^= a;
a ^= b;
// 现在 a = 2, b = 1
```

83
6. **加一**
L
labuladong 已提交
84

L
labuladong 已提交
85
```java
L
labuladong 已提交
86 87 88 89 90
int n = 1;
n = -~n;
// 现在 n = 2
```

91
7. **减一**
L
labuladong 已提交
92

L
labuladong 已提交
93
```java
L
labuladong 已提交
94 95 96 97 98
int n = 2;
n = ~-n;
// 现在 n = 1
```

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

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

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

看个图就很容易理解了:

L
labuladong 已提交
107
![](https://labuladong.github.io/algo/images/位操作/1.png)
108 109

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

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

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

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

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

```java
int hammingWeight(int n) {
L
labuladong 已提交
121 122 123 124 125 126 127 128 129
    int res = 0;
    while (n != 0) {
        n = n & (n - 1);
        res++;
    }
    return res;
}
```

L
labuladong 已提交
130 131 132
**2、判断一个数是不是 2 的指数**

力扣第 231 题「2 的幂」就是这个问题。
L
labuladong 已提交
133 134 135

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

L
labuladong 已提交
136
```java
L
labuladong 已提交
137 138 139 140 141
2^0 = 1 = 0b0001
2^1 = 2 = 0b0010
2^2 = 4 = 0b0100
```

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

L
labuladong 已提交
144 145
```java
boolean isPowerOfTwo(int n) {
L
labuladong 已提交
146 147 148 149 150
    if (n <= 0) return false;
    return (n & (n - 1)) == 0;
}
```

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

L
labuladong 已提交
153
异或运算的性质是需要我们牢记的:
154 155 156

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

L
labuladong 已提交
157 158 159 160 161 162
**1、查找只出现一次的元素**

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

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

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

L
labuladong 已提交
165 166
```java
int singleNumber(int[] nums) {
167 168 169 170 171 172 173 174
    int res = 0;
    for (int n : nums) {
        res ^= n;
    }
    return res;
}
```

L
labuladong 已提交
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 241 242 243 244
**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 已提交
245

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

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

250
**_____________**
L
labuladong 已提交
251

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

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


J
Jody Zhou 已提交
257 258
======其他语言代码======

B
brucecat 已提交
259 260 261 262 263 264 265 266
[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 已提交
267
[JodyZ0203](https://github.com/JodyZ0203)提供 191. 位1的个数 Python3 解法代码:
J
Jody Zhou 已提交
268

J
Jody Zhou 已提交
269
```Python
J
Jody Zhou 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
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 已提交
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 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
```



### 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;
}
```