LeetCodeAnimation/notes/LeetCode第201号问题:数字范围按位与.md
程序员吴师兄 5dee53d957 更换图片地址
2019-11-14 11:00:28 +08:00

62 lines
1.4 KiB
Java
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

# LeetCode 201 号问题数字范围按位与
> 本文首发于公众号五分钟学算法[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。
>
> 个人网站[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com)
题目来源于 LeetCode 上第 号问题题目难度为 Medium目前通过率为 39.1%
### 题目描述
给定范围 [m, n]其中 0 <= m <= n <= 2147483647返回此范围内所有数字的按位与包含 m, n 两端点
**示例 1:**
```
输入: [5,7]
输出: 4
```
**示例 2:**
```
输入: [0,1]
输出: 0
```
### 题目解析
[ 26 30] 为例
首先 [ 26 , 30 ] 的范围数字用二进制表示出来
**11**010  **11**011  **11**100  **11**101  **11**110
而输出 24 的二进制是 11000
可以发现只要找到二进制的 **左边公共部分** 即可
所以可以先建立一个 32 位都是 1 mask然后每次向左移一位比较 m n 是否相同不同再继续左移一位直至相同然后把 m mask 相与就是最终结果
### 动画描述
暂无
### 代码实现
```c++
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
unsigned int d = INT_MAX;
while ((m & d) != (n & d)) {
d <<= 1;
}
return m & d;
}
};
```
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/bjgx9.png)