Question
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 .
Analysis
给定一个大小为
例如 [5,7] ,返回 4 .
5&6&7=4
1 0 1 & 1 1 0 & 1 1 1=100
对于And操作,只要各位中有一个0,该位的结果便为0。当m和n有相同的左部时。m, n之间的任何一个数和m, n便有相同的左部。所以m, n共同的左部便是所求的结果。这样,我们便把m-n个数的运算换算成m, n两个数的运算,时间复杂度从
对m ,n进行右移操作,当m, n相等时。将共同头部回移到原来的位置,便是所得的结果。
Code
int rangeBitwiseAnd(int m, int n) {
int num=0;
while(m!=n){
m=m>>1;
n=n>>1;
num++;
}
return m<<num;
}