题目:
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: [5,7] Output: 4
Example 2:
Input: [0,1] Output: 0
代码:
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
if(m == n)
return m;
int res = m & n;
if(int(log(double(m))/log(double(2))) != int(log(double(n))/log(double(2))))
return 0;
int basebit = log(double(res)) / log(double(2)), topbit, resbit = 0;
int topm, topn;
while(basebit>=0){
topm = m & (1 << basebit);
topn = n & (1 << basebit);
if(topm != topn)
break;
basebit --;
resbit |= topm;
}
return resbit;
}
};