SDE & MLE Prep

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