sagelearnai

Bitwise AND of Numbers Range

Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #201

Return the bitwise AND of all numbers in [left, right], inclusive.

Examples

text
left = 5, right = 7          →  4     (101 & 110 & 111 = 100)
left = 0, right = 0          →  0
left = 1, right = 2147483647 →  0

Hints

  1. Any bit below the highest bit where left and right differ must take both values 0 and 1 somewhere in the range.
  2. So only the common prefix survives.

Approach

Shift both numbers right until they're equal, counting the shifts, then shift back: left << shift. Equivalently, while right > left: right &= right − 1 clears the low bits of right until it's ≤ left, and the result is right.

Why? If left and right differ at bit k, the range contains a number ending in 0111…1 and the next one ending in 1000…0 at bits ≤ k, so every bit ≤ k ANDs to 0. O(log right).

Complexity

Time: O(log right). Space: O(1).

Python solution
def rangeBitwiseAnd(left, right):
    shift = 0
    while left != right:
        left >>= 1
        right >>= 1
        shift += 1
    return left << shift
JavaScript solution
function rangeBitwiseAnd(left, right) {
  while (right > left) right &= right - 1;
  return right;
}