LeetCode 201. Bitwise AND of Numbers Range

来源:互联网 发布:舞霸王跳舞软件 编辑:程序博客网 时间:2024/06/03 17:02

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;    }


0 0
原创粉丝点击