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.

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

 

题目很简单,就是计算从n~m所有整数的与运算的结果,但是如果只是从n~m算一遍,会超时。

思路:

1. 如果n!=m,则n~m之间必定存在一个奇数和一个偶数,则与的结果中,最后一位一定是0;

2. 重复将n,m右移1位直到n==m,就能直到结果的末尾有多少个0,而高位与原来的n的高位相同。

代码如下:

public int rangeBitwiseAnd(int m, int n) {
        int mc = m;
        int a = -1;
        while(m != n) {
            m >>= 1;
            n >>= 1;
            a <<= 1;
        }
        return mc & a;
    }

 

posted on 2015-04-20 18:14  linxiong1991  阅读(89)  评论(0编辑  收藏  举报

导航