hardBit ManipulationPure DSA~25 min
Bitwise AND of All Numbers in a Range
Compute the bitwise AND of every integer in the inclusive range [left, right] without iterating through all of them.
Problem
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Input
Two integers left and right with left <= right.
Output
An integer: the bitwise AND across the range.
Constraints
- 0 <= left <= right <= 2^31 - 1
- The range can be enormous.
- Iterating element by element is too slow.
Examples
Example 1
Input
left = 5, right = 7
Output
4
5 & 6 & 7 = 4.
Example 2
Input
left = 1, right = 2147483647
Output
0
The full range ANDs to 0.