Article Directory
Subject: 201. Bitwise AND of Number Range
Given a range [m, n], where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range (including the two ends of m, n).
Example 1:
输入: [5,7]
输出: 4
Example 2:
输入: [0,1]
输出: 0
Source: LeetCode
Link: https://leetcode-cn.com/problems/bitwise-and-of-numbers-range
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Basic idea: the longest common prefix of the boundary
- Remove the non-public part by shifting right, and count the number of digits in the public part
- Move the common part back by moving the previous result left
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
//这道题有一定的技巧性,直接进行位于运算,会导致一些测试用例运行超时
//这里转化为求m,n的最长公共前缀
int cnt = 0;
while(m < n){
m = m >> 1;
n = n >> 1;
++cnt;
}
return m << cnt;
}
};