Bitwise and of Numbers Range
Original title link bitwise AND of Numbers Range
Calculating the results of all numbers in the range of [m:n] [m:n] [m:n]
First you need to clarify a few knowledge points a& (a+1) A & (A + 1) a \& (A + 1) the lowest bit must be 0 0&b 0 & B 0 \& b The result must be 0 a& (a+1) & (A + 2) &...& (A+k) A & (A + 1) & (A + 2) & ... & (A + K) a \& (A + 1) \& (A + 2) \& The lowest bit of \& (A + K) must be 0.
So if n > m, then [M:N] [m:n] [m:n] in the range of all elements and the lowest bit of the result of the operation must be 0, so there is
All_nums_and (m, n) = All_nums_and (M >> 1, n >> 1) << 1
Where All_nums_and (M, n) represents the result of all the elements in the range [m:n] [m:n] [m:n]
The code is as follows
Class Solution {public
:
int rangebitwiseand (int m, int n) {
return n <= m? M:rangebitwiseand (M >> 1, n >> 1) << 1;
}
};