InterviewPrepKit

Home / Coding / Bit Manipulation

Bitwise AND of Numbers Range

medium Original β†—
Solving tips
  • Key insight: a bit survives the AND only if it is 1 in every number of the range; low bits churn through 0 and 1 and die, so the answer is exactly the common binary PREFIX of left and right.
  • Method 1: right-shift both left and right until equal (counting shifts), then shift the shared value back left, left << shift.
  • Method 2 (Brian Kernighan): repeatedly clear right's lowest set bit with right &= right-1 while left < right; the result is the common prefix.
  • Target O(log n) time, O(1) space, never iterate the range (it can hold billions); left=0 naturally yields 0.

Problem

Given two integers left and right with left <= right, return the bitwise AND of every integer in the inclusive range [left, right] β€” that is, left & (left + 1) & ... & right.

Examples

  • left = 5, right = 7 β†’ 4 β€” 101 & 110 & 111 = 100 = 4.
  • left = 0, right = 0 β†’ 0 β€” a single number ANDed with nothing else is itself.
  • left = 1, right = 2147483647 β†’ 0 β€” such a huge range clears every bit.

Constraints

  • 0 <= left <= right <= 2^31 - 1

The range can hold billions of numbers, so you cannot actually loop over it β€” the AND must be found structurally, in about O(log n) steps.

Think about it first

Hint 1 A bit is `1` in the answer only if it is `1` in *every* number of the range. The moment any number in the range has a `0` there, that bit is dead. Which bits can possibly stay `1` across a contiguous run of integers?
Hint 2 Low bits flip constantly as you count upward, so they get zeroed. Only the high bits that `left` and `right` already share β€” their common binary prefix β€” can survive. The answer is that prefix, padded with zeros.
Hint 3 Right-shift both `left` and `right` until they become equal (that's the common prefix), counting the shifts, then shift the prefix back left. Alternatively, keep clearing the lowest set bit of `right` (`right &= right - 1`) until `right <= left`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.