题目链接:
https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
难度:中等
201. 数字范围按位与
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
这个题 怎么说呢 有点迷
找规律 发现是数字范围内的最长公共前缀 然后。。。 也就是最大值 最小值的最长公共前缀 题解上有证明。。。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int s=0;
while(m<n){
m>>=1;
n>>=1;
++s;
}
return m<<s;
}
};
还有个方法 Brian Kernighan 算法 第一次听说
n&(n-1) 就是将 n 最右边的1 抹去变为 0 利用这个性质 寻找最长前缀
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while(m<n){
n=n&(n-1);
}
return n;
}
};
总之 一句话 找最长公共前缀