Leetcode 201. Bitwise AND of Numbers Range
Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Input: left = 5, right = 7 Output: 4
Input: left = 0, right = 1 Output: 0
left and right, one approach could be to perform the bitwise AND operation iteratively on each number in the range. However, this might be inefficient for large ranges.left and right by shifting both to the right until they are equal. The remaining bits after shifting left back to the original places will form the result.left and right.left is not equal to right, right shift both left and right until they are equal.left back to its position to get the result.public class Solution {
public int rangeBitwiseAnd(int left, int right) {
// Count the number of shifts
int shift = 0;
while (left < right) {
left >>= 1;
right >>= 1;
shift++;
}
// Shift the result back to its original position
return left << shift;
}
}
left and right. This is because the number of shifts will be proportional to the number of bits in the binary representation of right.left and right are right-shifted until they become equal:
left and right.shift counts how many bits have been shifted out.This method ensures that we perform the necessary bitwise operations efficiently without having to AND every number in the range.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?