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.

 

1、首先换成2进制,如果长度不一样,那么一定是0.

然后从较大的位置开始判断,如果均为1,那么该位置为1,均为0,判断下一位,如果不一样,那么就返回结果。

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int len1 = getLen(m);
        int len2 = getLen(n);
        if (len1 != len2 || m == 0){
            return 0;
        }
        int result = (1 << (len1 - 1));
        for (int i = len1 - 2; i >= 0; i--){
            if (((m >> i) & 1) == 1 && ((n >> i) & 1) == 1){
                result += (1 << i);
            } else if (((m >> i) & 1) == 0 && ((n >> i) & 1) == 0){
                continue;
            } else {
                return result;
            }
        }
        return result;
    }
    public int getLen(int n){
        int result = 0;
        while (n != 0){
            result++;
            n /= 2;
        }
        return result;
    }
}

 

 

2、参考discuss,发现更简单的做法= =。虽然代码更少,但是判断次数应该是比第一重要多的。

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int i = 0;
        for (; m != n; ++i) {
            m >>= 1;
            n >>= 1;
        }
        return n << i;
    }
}