数字范围按位与
方法一:位移
给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。
不同通信协议数据交换需要用到位对齐
例如在CANOPEN协议中,驱动器初始化数据的位数并不相同,
EtherCat——>初始数据——>canopen
需要对初始数据做处理:在主站中补齐32位,在从站中检测高位,在对其做拆分处理。
示例 1:
输入: [5,7]
输出: 4
示例 2:
输入: [0,1]
输出: 0
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
// 找到公共前缀
while (m < n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int shift = 0;
// 找到公共前缀
while (m < n) {
m >>= 1;
n >>= 1;
++shift;
}
return m << shift;
}
};
方法二:Brian Kernighan 算法
class Solution {
public int rangeBitwiseAnd(int m, int n) {
while (m < n) {
// 抹去最右边的 1
n = n & (n - 1);
}
return n;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/solution/shu-zi-fan-wei-an-wei-yu-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。