← Bit Manipulation

Drill #88 — Bitwise AND of range

Medium Bit Shift Bit Manipulation

In plain English: AND all integers from m to n together. Find the result without looping through every number.

Any bit that flips between m and n will become 0 in the AND. Shift both right until they match โ€” the common prefix is the answer, shifted back.

Prompt

Given a range [m, n] where 0 <= m <= n, return the bitwise AND of all numbers in this range.

Try to write it from scratch before scrolling down.

Solution

def range_bitwise_and(m, n):
    shift = 0
    while m != n:
        m &gt;&gt;= 1
        n &gt;&gt;= 1
        shift += 1  # count how many bits differ
    return m &lt;&lt; shift  # common prefix, shifted back

# Test: range_bitwise_and(5, 7) == 4   (101 &amp; 110 &amp; 111 = 100)
# Test: range_bitwise_and(0, 0) == 0
# Test: range_bitwise_and(1, 2147483647) == 0
O(log n) time ยท O(1) space

Related Micro Drills

← Drill #87 Drill #89 →