201. Bitwise AND of Numbers Range
Problem
Return the bitwise AND of every integer in the range [left, right], inclusive.
Example: left = 5, right = 7 → 4; left = 1, right = 2147483647 → 0
Any bit that flips somewhere in [left, right] becomes 0. The result is the common binary prefix of left and right: shift both right until equal, then shift back.
Complexity: O(32).
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
shift = 0
while left != right:
left, right, shift = left >> 1, right >> 1, shift + 1
return left << shift
assert Solution().rangeBitwiseAnd(5, 7) == 4
assert Solution().rangeBitwiseAnd(0, 0) == 0
assert Solution().rangeBitwiseAnd(1, 2147483647) == 0
class Solution {
public int rangeBitwiseAnd(int left, int right) {
while (right > left) right &= right - 1; // drop lowest set bits until within the prefix
return right;
}
}
func rangeBitwiseAnd(left int, right int) int {
shift := 0
for left != right { // the answer is the common binary prefix
left, right = left>>1, right>>1
shift++
}
return left << shift
}