Bitwise AND of Numbers Range
MediumTop Interview 150 Bit ManipulationProblem
Given two integers left and right with left ≤ right, take every integer
from left to right inclusive and combine them all with bitwise AND.
Return that result. The range can contain over two billion numbers, so the answer must come from the bit patterns, not from a loop over the whole range.
Constraints
- 0 ≤ left ≤ right ≤ 2³¹ − 1
Examples: pick one to animate
Solutions
Time: Each loop drops one bit, and a 31-bit number needs at most 31 drops.
Space: Just a shift counter and the two numbers.
Counting up from left to right flips low bits again and again, so every bit below the first place where left and right differ is 0 at some point in the range, and the AND clears it. The bits above that place never change, so they survive. Find that shared prefix by shifting both numbers right until they are equal, counting the shifts, then shift the prefix back left by that count.