This problem looks busy at first, but the accepted solution is built around one steady invariant. For 201.Bitwise AND of Numbers Range, the solution in this repository is mainly a bit manipulation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: bit manipulation.
The notes already sitting in the source point us in the right direction:
- bit operation
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are rangeBitwiseAnd.
Guide
Why?
The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Start from the smallest reliable state.
- Expand one legal move at a time.
- Cache, count, or merge information as soon as it becomes settled.
- Let the final stored value answer the original question.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//bit operation
02class Solution {
03public:
04 int rangeBitwiseAnd(int m, int n) {
05 if(m == 0) return 0;
06 //log(0) is not defined
07 int mb = log2(m), nb = log2(n);
08
09 if(mb != nb) return 0;
10
11 int ans = 0;
12
13 //examine one bit at a time
14 while(mb == nb){
15 //remove that bit once examined
16 ans += (1 << mb);
17 m -= (1 << mb);
18 n -= (1 << mb);
19 if(m == 0) break;
20 mb = log2(m);
21 nb = log2(n);
22 };
23
24 return ans;
25 }
26};
27
28//https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/531/week-4/3308/discuss/593317/Simple-3-line-Java-solution-faster-than-100
29class Solution {
30public:
31 int rangeBitwiseAnd(int m, int n) {
32 while(n > m){
33 /*
34 suppose a >= b
35 the result of a & b must <= min(a, b) = b,
36 so we can skip numbers between b and (a&b)
37 */
38 n &= (n-1);
39 }
40 return n & m;
41 }
42};
Cost