Bitwise AND of a number range keeps common prefix bits of low and high boundaries. Shift left until low == high, then shift back.
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> bool:
shifts = 0
while left < right:
left >>= 1
right >>= 1
shifts += 1
return left << shifts
class Solution {
public int rangeBitwiseAnd(int left, int right) {
int shifts = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shifts++;
}
return left << shifts;
}
}