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.
分析:
5:101
6:110
7:111
在对5、6、7按位与时,对应的位上,若存在不同元素,则该位与后的结果为0。因此,本题找出相同位即可。例如从5~7,相同的位只有最高位,那么最后结果就应该为100。
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int len=0;
while(m!=n){
m=m>>1;
n=n>>1;
len++;
}
m=m<<len;
return m;
}
};