`

Leetcode - Bitwise AND of Number 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.

[分析] 因为 0 <= m, n <= Integer.MAX_VALUE, O(N)的解法是不可接受的,因此可推断是一道数学题。耐心多举例下,会发现结果的规律是m 和 n最左边的连续公共部分。
[ref]
http://www.cnblogs.com/grandyang/p/4431646.html

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int mask = -1;
        while ((m & mask) != (n & mask)) {
            mask <<= 1;
        }
        return m & mask;
    }
    public int rangeBitwiseAnd2(int m, int n) {
        int i = 0;
        while (m != n) {
            m >>= 1;
            n >>= 1;
            i++;
        }
        return m << i;
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics