201. Bitwise AND of Numbers Range

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.

If two numbers cross the boundary of 2^x, i.e. m < 2^x < n, this means there is no common 1s exist in all the number. so the real question is to find the left-most common 1s, if any.

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int res = 0;
        while( m != n){
            m >>= 1;
            n >>= 1;
            res++;
        }

        return m << res;
    }
}

results matching ""

    No results matching ""