Given a range [M, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, Inclus Ive.
For example, given the range [5, 7], and you should return 4.
This is a bit operation.
One basic formula to explore is (N & (n-1))
Suppose there is such a number xxxxxxxxxxx10000 (this indicates that the rightmost one is a bit of 1, and X is 1 can be 0)
So n-1 = xxxxxxxxxxx01111
N & (n-1)?
We found that the 1 right side was eliminated.
Wait, there seems to be information to explore n = xxxxxxxxxxx10000, n-1 = xxxxxxxxxxx01111, N & (n-1) = xxxxxxxxxxx00000
Have you found that the difference between N and (N & (n-1)) is not more than 1 ah, so what is the number of this between the form??
n = xxxxxxxxxxx10000
N-1 = xxxxxxxxxxx01111
xxxxxxxxxxx01110
......
Xxxxxxxxxxx0xxxx
......
N & (n-1) = xxxxxxxxxxx00000
Did you find out that all these numbers and the result is N & (n-1)
So the solution is very concise:
int Rangebitwiseand (int m, int n) { while (n > M) n &= n-1; return n; }
Leetcode Bitwise and of Numbers Range