LeetCode 201. 数字范围按位与(Bitwise AND of Numbers Range)
作者:互联网
201. 数字范围按位与
201. Bitwise AND of Numbers Range
题目描述
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
LeetCode201. Bitwise AND of Numbers Range中等
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
Java 实现
方法一
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int d = Integer.MAX_VALUE;
while ((m & d) != (n & d)) {
d <<= 1;
}
return m & d;
}
}
方法二
class Solution {
public int rangeBitwiseAnd(int m, int n) {
int count = 0;
while (m != n) {
m >>= 1;
n >>= 1;
count++;
}
return m << count;
}
}
参考资料
- https://leetcode.com/problems/bitwise-and-of-numbers-range/
- https://www.cnblogs.com/grandyang/p/4431646.html
- https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
标签:201,int,Bitwise,Range,Numbers,https 来源: https://www.cnblogs.com/hglibin/p/10962434.html