LeetCode 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.


Suppose our given range is 5 : 0101 ---- 7: 0111

Thus, we can see that the lower 2 bits are different. By shifting them to right, we can finally make m == n. thus, result will be m << count;


Code copied from the discussion. But this method is very fantastic!!

    int rangeBitwiseAnd(int m, int n) {
        int count = 0;
        while(m != n) //until the left identical bits, all the right will be cancelled by increments from m to n;;
        {
            m >>= 1;
            n >>= 1;
            count++;
        }
        return m << count;
    }


你可能感兴趣的:(LeetCode 201. Bitwise AND of Numbers Range)