AND together every number from left to right. Only the shared leading bits survive, so shift both ends right until they match.
▼The problem
LeetCode 201 (Medium). Given two integers left <= right (0 to 2³¹ − 1), return the bitwise AND of every integer in the range [left, right].
Examples: [5, 7] → 4 (101 & 110 & 111 = 100).
The solution
def rangeBitwiseAnd(left, right):
shift = 0
while left < right: # they differ: drop a bit
left >>= 1
right >>= 1
shift += 1
return left << shift # prefix, then zerosTranscript
Bitwise AND of Numbers Range. You're given two numbers, left and right. AND together every whole number from left to right, and return the result.
Take five to seven: one oh one, one one oh, and one one one. AND keeps a bit only where every number has a one. Only the top bit survives, so the answer is four.
The simple way ANDs the numbers one by one. That's fine for three numbers, but a range can hold over two billion, and so could the loop.
Here's a better picture. Each bit is a candle, lit for one and dark for zero. AND keeps a candle burning only if it's lit in every number. So, counting from left to right, a candle that goes dark even once is out for good.
So which candles survive? Say left is twenty-one and right is twenty-six. Find the first bit where they differ. Left has a zero there, so that candle goes out. And on the way up, the count rolls over at twenty-four, where every bit below it is zero, so those go out too. The bits above never change. The answer is their shared prefix, then zeros: sixteen.
In code, shift both numbers right until they're equal, counting the shifts. What's left is the shared prefix. Shift it back left by that count, and the dropped bits return as zeros.
Try twenty-six to thirty. Light all five candles. Twenty-six puts out the four and the one. Twenty-seven changes nothing. Twenty-eight puts out the two. Twenty-nine and thirty change nothing, so sixteen and eight stay lit: twenty-four.
The shifts agree. Twenty-six and thirty become thirteen and fifteen, then six and seven, then three and three. Equal after three shifts. Shift the three back three places: twenty-four.
Each shift drops a bit, so thirty-two bit numbers need at most thirty-two shifts, however wide the range. That's order log right time, and constant space.
Find the shared prefix, then pad with zeros. That's Bitwise AND of Numbers Range.