Bitwise AND Across a Range

medium bit manipulation

Problem

Given two non-negative integers left ≤ right, return left & (left+1) & … & right.

Inputleft = 5, right = 7
Output4
The answer is the common high-bit prefix of left and right (any bit that flips inside the range becomes 0). Repeatedly drop the lowest set bit of right until right ≤ left.

def range_bitwise_and(left, right):
    while right > left:
        right &= right - 1
    return right
function rangeBitwiseAnd(left, right) {
  while (right > left) right &= right - 1;
  return right;
}
class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        while (right > left) right &= right - 1;
        return right;
    }
}
int rangeBitwiseAnd(int left, int right) {
    while (right > left) right &= right - 1;
    return right;
}
Time: O(log right) Space: O(1)