CodingNodes / Bit Manipulation / Bitwise AND of Numbers Range System design Space play · ←→ step · R restart

Problem

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

TimeO(log right) SpaceO(1)

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.