1. Iterative Accumulator
Intuition
Initialize res = left. Loop for i from left + 1 to right, computing res &= i. If res becomes 0 at any point, return 0 immediately since AND with 0 stays 0.
When to apply: When right - left is guaranteed to be small (< 105).
Algorithm
- Step 1: Initialize res = left.
- Step 2: Loop i from left + 1 to right. Compute res &= i.
- Step 3: If res == 0, break early and return 0.
- Step 4: Return res after loop completes.
#include <iostream> using namespace std; int rangeBitwiseAndBrute(int left, int right) { long long res = left; for (long long i = (long long)left + 1; i <= right; ++i) { res &= i; if (res == 0) return 0; } return (int)res;} int main() { cout << "Brute (5, 7): " << rangeBitwiseAndBrute(5, 7) << endl; // 4 cout << "Brute (0, 0): " << rangeBitwiseAndBrute(0, 0) << endl; // 0 return 0;}Time & Space Complexity
- Time complexity:
O(R - L) - Space complexity:
O(1)