Bitwise AND of Numbers Range

2019-05-25 22:48:31 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int mask = INT_MAX;
        while((m & mask) != (n & mask)) {
            mask <<= 1;
        }
        return m & mask;
    }
};
  • Version 2
代码语言:javascript复制
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        int count = 0;
        while(m != n) {
            m >>= 1;
            n >>= 1;
            count  ;
        }
        return m << count;
    }
};
  • Version 3
代码语言:javascript复制
class Solution {
public:
    int rangeBitwiseAnd(int m, int n) {
        while(m < n) {
            n &= n - 1;
        }
        return n;
    }
};

0 人点赞