https://leetcode.com/problems/bitwise-and-of-numbers-range/

Brutal

Use loop for every number between m and n, & together. O(n - m)

Revision 1

To bitwise and two number n1 and n2 is to take the common set bits. eg: 1100 & 1011 = 1000.
So, we only need to find the common 1s for all of the number from m to n:

1
2
3
4
5
6
7
int shift = 0;
while (n != m) {
n >>= 1;
m >>= 1; // right shift n and m together at the same time,
shift++; // if n == m, then it is the common "are" they have
}
return n << shift;

Revision 2

Like the number-of-1-bits
The n & (n - 1) will remove the right most set bit to 0, this is like moving one step
closer to m. Or, in other word, making it more “alike” to m.

1
2
3
4
5
6
7
8
public class Solution {
public int rangeBitwiseAnd(int m, int n) {
while (n > m) {
n &= n - 1;
}
return n;
}
}