Bitwise AND of Numbers Range
Medium
Topics
Given two integers a and b with a <= b, return the bitwise AND of all numbers in the inclusive range [a, b].
Example 1
Input: a = 5, b = 7 Output: 4
Example 2
Input: a = 0, b = 0 Output: 0
Example 3
Input: a = 26, b = 30 Output: 24
Constraints
- 0 <= a <= b <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
AND-ing a whole range can only keep a bit that is set in every number of the range. Walk the bits from the top: the high bits where a and b already agree are constant across the range, and everything below the first disagreement must be zero.
Why the low bits vanish: if a and b differ at bit k, the range spans a point where bit k flips, and crossing it forces every bit below k through a zero. So the answer is the common binary prefix of a and b, padded with zeros — which is exactly what shifting both right until they meet and shifting back computes.
Approach
- Shift
aandbright together, counting the shifts, until they are equal. - That shared value is the common prefix.
- Shift it back left by the count.
Dry Run
a = 5 (0b101) b = 7 (0b111)
a b binary a binary b
5 7 101 111 differ -- shift
2 3 10 11 differ -- shift
1 1 1 1 equal -- common prefix is 1, after 2 shifts
answer 1 << 2 = 4
spot checks against brute force
[5, 7] -> 4
[0, 0] -> 0
[2147483646, 2147483647] -> 2147483646
[1, 2147483647] -> 0Complexity
- Time — O(log b): at most 31 shifts at the stated bound, since each iteration drops a bit.
- Space — O(1).
Common Pitfalls
- Looping over the range and AND-ing. The range reaches 2³&sup9; values, so this is not a slow solution, it is a non-terminating one.
- Returning
a & b. That keeps bits the endpoints happen to share, but a bit can be set at both ends and clear in between —[5,7]gives5 & 7 = 5, while the true answer is 4. - Shifting only one of the two operands, which loses the alignment that makes the prefix meaningful.
- Forgetting the
a == 0case. It needs no special handling — the loop shiftsbdown to 0 and returns 0 — but say so rather than adding a branch. - Using a signed right shift on a value near 2³&sup9;-1 in a language where the top bit matters. The constraints keep everything non-negative, so a logical shift and an arithmetic shift agree here; on the full 32-bit range they would not.
Full Solution — all languages
class Solution:
def rangeBitwiseAnd(self, a, b):
shift = 0
while a < b:
a >>= 1
b >>= 1
shift += 1
return a << shiftimport java.util.*;
class Solution {
public int rangeBitwiseAnd(int a, int b) {
int shift = 0;
while (a < b) {
a >>= 1;
b >>= 1;
shift++;
}
return a << shift;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int rangeBitwiseAnd(int a, int b) {
int shift = 0;
while (a < b) {
a >>= 1;
b >>= 1;
shift++;
}
return a << shift;
}
};/**
* @param {number} a
* @param {number} b
* @return {number}
*/ var rangeBitwiseAnd = function(a, b) {
let shift = 0;
while (a < b) {
a >>= 1;
b >>= 1;
shift++;
}
return a << shift;
};