Skip to content
BytePatterns

Bitwise AND Across a Range

MediumBit Manipulation#common-prefix#bit-shift~20m

Problem

A network tool needs the widest mask shared by a block of consecutive addresses. Given two integers lo and hi with 0 ≤ lo ≤ hi ≤ 2^31 - 1, return the bitwise AND of every integer from lo to hi, inclusive. The range can hold about two billion numbers, so looping over it is far too slow.

Examples

Input:  lo = 5, hi = 7
Output: 4
Why:    101 & 110 & 111 = 100
Input:  lo = 12, hi = 15
Output: 12
Why:    1100 through 1111 all share the prefix 11, and the low two bits take every value
Input:  lo = 1, hi = 2147483647
Output: 0
Why:    edge case, the range crosses a power of two, so no bit survives

Hints

0 / 3

Stuck on the idea rather than the code? Masks and Power of Two covers it.