这题有很多思路,如果直接从m与到n,会TLE
思路一:
the result of a range bitwise AND is the common 'left header' of m and n.(find the leftmost common digits of m and n)
class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int commonBit = 0;
while(m != n){
m >>= 1;
n >>= 1;
commonBit++;
}
return m << commonBit;
}
};
思路二:
当m到n之前如果跨过了1,2,4,8等2^i次方的数字时(即判断m与n是否具有相同的最高位),则会为0,否则顺序将m到n相与
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
int bitm = 0,bitn = 0;
for(int i = 0; i < 31; i++){
if(m & (1 << i)) bitm = i;
if(n & (1 << i)) bitn = i;
}
if(bitm == bitn){
int res = m;
for(int j = m; j < n; j++){ //这个地方之所以不用j <= n,是因为这个测试用例:<span style="color: rgb(85, 85, 85); line-height: 35px;">2147483646, 2147483647</span>
res = res & j; //<span class="comment" style="margin: 0px; padding: 0px; border: none; color: rgb(0, 130, 0); line-height: 18px;">2147483647+1 会超过范围</span><span style="margin: 0px; padding: 0px; border: none; line-height: 18px;"> </span>
}
res = res & n;
return res;
}else{
return 0;
}
}
};</span>
还有一种方法:
n&(n-1)会消除n中最后一个1,如1100000100当与n-1按位与时便会消除最后一个1,赋值给n(这样就减免了很多不必要按位与的过程)
<span style="font-family:Microsoft YaHei;font-size:14px;">class Solution {
public:
int rangeBitwiseAnd(int m, int n) {
while(n > m){
n &= n - 1;
}
return n;
}
};</span>
参考:http://blog.csdn.net/lu597203933/article/details/44811049