Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
观察连续若干个数在各个bit上的分布情况,可以得出分布规律。在第k位,总是会交替出现2^(k-1)个0和2^(k-1)个1.所以如果n-m+1大于2^(k-1),则在后k位的每一位上,至少会有一个数是0,所以n-m+1个数的AND和在后k位上必然都是0. 至于在高于k位的,这n-m-1个是在这个位上要么都是0要么都是1,要么m是0而n是1,要么m是1而n是0.
算法时间复杂度为log(n-m+1)
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
//连续若干个数在第k位上总是2^(k-1)个0、2^(k-1)个1交替出现,这是解答本题的关键
long long tmp = 1,k = 0;
while(tmp < n-m+1){ tmp<<=1; k++; } //tmp==2^k >= n-m+1;
k+=1; //2^(k-1)>=n-m+1;
tmp = 1;
int res = 0;
for(; (tmp<<(k-1)) <= m; k++){ //若2^(k-1) > m,则说明至少m在第k位是0
if((tmp<<(k-1))<n-m+1) continue; //2^(k-1) < n-m+1说明n-m+1个连续的数中至少有1个数在第k位是0
int a = (m>>(k-1))&1; //求m的第k位
int b = (n>>(k-1))&1; //n的第k位
if(a==1 && b==1) res += (1<<(k-1)); //说明[m,n]所有的数的第k位都是1
}
return res;
}
};