Practice › Bit Manipulation
Bitwise AND of a Range
Medium · Bit Manipulation · Asked at Amazon, Microsoft, Google
For each query l r, print l & (l + 1) & … & r — the bitwise AND of every integer from l to r.
Input
First line: q. Next q lines: l r.
Output
q lines — the AND of each range.
Constraints
- 1 ≤ q ≤ 10^5
- 0 ≤ l ≤ r < 2^31
Any bit below the highest bit where l and r differ takes both values inside the range, so it ANDs to 0. The answer is the common prefix of l and r: shift both right until they are equal, then shift back.
Example 1
Input
3 5 7 0 0 1 2147483647
Output
4 0 0
Hints
- If l and r differ in some bit, then somewhere between them that bit and every lower bit take the value 0.
- Only the common high-order prefix of l and r survives.
- Shift both right until they are equal; count the shifts.
Approach
While l ≠ r, shift both right by one and count the shifts. The remaining value is their common prefix; shift it back left by the count. Lower bits are all zeroed because the range crosses a point where they are all 0 (just after r's prefix rolls over). At most 31 shifts per query.
Complexity: O(31) per query
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int q;
cin >> q;
while (q--) {
long long l, r;
cin >> l >> r;
int shift = 0;
while (l != r) {
l >>= 1;
r >>= 1;
shift++;
}
cout << (l << shift) << "\n";
}
return 0;
}Python solution
import sys
data = list(map(int, sys.stdin.read().split()))
q = data[0]
out = []
for i in range(q):
l, r = data[1 + 2 * i], data[2 + 2 * i]
shift = 0
while l != r:
l >>= 1
r >>= 1
shift += 1
out.append(l << shift)
print("\n".join(map(str, out)))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int q = (int) in.nval;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
in.nextToken();
long l = (long) in.nval;
in.nextToken();
long r = (long) in.nval;
int shift = 0;
while (l != r) {
l >>= 1;
r >>= 1;
shift++;
}
sb.append(l << shift).append('\n');
}
System.out.print(sb);
}
}