← Back to Leo Academy Masterclass

Problem #201: Bitwise AND of Numbers Range

Medium Bit Manipulation

Intuition & Strategy Breakdown

Bitwise AND of a number range keeps common prefix bits of low and high boundaries. Shift left until low == high, then shift back.

Python Solution

class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> bool:
        shifts = 0
        while left < right:
            left >>= 1
            right >>= 1
            shifts += 1
        return left << shifts

Java Solution

class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        int shifts = 0;
        while (left < right) {
            left >>= 1;
            right >>= 1;
            shifts++;
        }
        return left << shifts;
    }
}
Watch Interactive Video on Leo Academy Main App