Shift left and right down together counting shifts until equal; shift back up.
Approach 1
class Solution {
public int rangeBitwiseAnd(int left, int right) {
int shift = 0;
while (left != right) { left >>= 1; right >>= 1; shift++; }
return left << shift;
}
}
Verdict: Never touches the range itself.
2
Clear right's low bits
Time O(number of ones) Space O(1)
While right > left: right &= right − 1 (drop its lowest set bit).
Approach 2
class Solution {
public int rangeBitwiseAnd(int left, int right) {
while (right > left) right &= right - 1;
return right;
}
}
Verdict: Same prefix, different route.
Before you submit
Edge cases and common mistakes
Test these inputs
left == right
Range crossing a power of two (0 below it)
Mistakes people make
Looping from left to right (up to 2³¹ iterations).