Problem 482
Bitwise AND of a Range
Medium · 20 pts · Bit Manipulation
Problem
Compute the bitwise AND of all integers from L to R inclusive. The range can contain up to two billion numbers, so you cannot loop over it. Any bit that changes somewhere in the range becomes 0 in the result, so the answer is the common binary prefix of L and R followed by zeros. Shift both numbers right until they are equal, then shift back.
Input
Two integers L and R.
Output
Print the bitwise AND of all numbers in [L, R].
Constraints
0 <= L <= R <= 2147483647
Example input
5 7
Example output
4
Explanation
5 = 101, 6 = 110 and 7 = 111. Only the highest bit is set in all three, so 5 AND 6 AND 7 = 100 = 4.