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.
Analysis: The first is easy to think of, will all the numbers and operation, definitely timed out
1 classSolution {2 Public:3 intRangebitwiseand (intMintN) {4 intresult =1;5 for(inti = m; I <= N; i++) result = result &i;6 returnresult;7 }8};View Code
Because it is a sequential integer and, the result of this bit is 0 if there is a number 0 on one bit.
If the number of n digits >m, there will be 100 ... 0 of the cases, and the result is 100 ... 00
If the number of n digits is =m, starting with the highest bit, if N and M are equal, consider the next bit until a bit is n=1,m=0 (because N>m). In this case, there will be a 100 ... 0, so the result of the and operation of the subsequent numbers is 0.
Therefore, the M and N are constantly shifted to the right, and counted against the counter until m=n.
Run time 229ms. Think about how to optimize it.
1 classSolution {2 Public:3 intRangebitwiseand (intMintN) {4 intTimes =0;5 while(M! =N) {6m = M >>1;7n = n >>1;8times++;9 }Ten returnm<<Times ; One } A};
Bitwise and of Numbers Range