Bitwise AND Across a Range
Problem
Given two non-negative integers left ≤ right, return left & (left+1) & … & right.
Input
left = 5, right = 7Output
4The 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;
}