InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Bitwise AND of Numbers Range

medium Original ↗ 00:00

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 = 74101 & 110 & 111 = 100 = 4.
  • left = 0, right = 00 — a single number ANDed with nothing else is itself.
  • left = 1, right = 21474836470 — the range is wide enough that no bit is set in every number.

Constraints

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

The range can contain billions of numbers, so iterating over it is infeasible. 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. As soon as any number in the range has a `0` there, that bit becomes `0` in the result. Which bits can 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`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug