题目链接:
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
How to say this question is a bit confusing.
Find the rule and find that it is the longest common prefix in the number range. . . That is, the longest common prefix problem of the maximum and minimum values is proved. . .
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int s=0;
while(m<n){
m>>=1;
n>>=1;
++s;
}
return m<<s;
}
};
There is another method, the Brian Kernighan algorithm, the first time I heard that
n&(n-1) is to erase the rightmost 1 of n into 0. Use this property to find the longest prefix
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while(m<n){
n=n&(n-1);
}
return n;
}
};
In short, find the longest common prefix in one sentence