Skip to content

Bitwise AND of Numbers Range⚓︎

Link

Description⚓︎

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Example 1:

  • Input: left = 5, right = 7
  • Output: 4

Example 2:

  • Input: left = 0, right = 0
  • Output: 0

Example 3:

  • Input: left = 1, right = 2147483647
  • Output: 0

Constraints:

  • 0 <= left <= right <= 2^31 - 1

Solution⚓︎

Way 1⚓︎

class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        int res = 0;
        for (int i = 30; i >= 0; i--) {
            if ((right >> i & 1) != (left >> i & 1)) break;
            if (right >> i & 1) res += 1 << i;
        }
        return res;
    }
};

Way 2⚓︎

See reference (Chinese).

class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        int shift = 0;
        while (left < right) {
            left >>= 1;
            right >>= 1;
            shift++;
        }
        return left << shift;
    }
};
  • Time complexity: \(O(\log right)\);
  • Space complexity: \(O(1)\).

Way 3⚓︎

1
2
3
4
5
6
7
8
9
class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right = right & (right - 1);
        }
        return right;
    }
};
  • Time complexity: \(O(\log right)\);
  • Space complexity: \(O(1)\).