201. Bitwise AND of Numbers Range
Description
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Example 1:
Input: left = 5, right = 7 Output: 4
Example 2:
Input: left = 0, right = 0 Output: 0
Example 3:
Input: left = 1, right = 2147483647 Output: 0
Constraints:
0 <= left <= right <= 231 - 1
Solutions
Solution 1
Thinking
AND-ing every integer in \([left,right]\) is impossible when the span approaches \(2^{31}\). The bitwise AND of a contiguous range is their common binary prefix: lower bits are cleared by some number in the range.
While \(left < right\), clear the lowest set bit of \(right\) (\(right \mathrel{\&}= right-1\)) until \(right \le left\). The remaining \(right\) is that common prefix.
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 | |