def Rangebitwiseand(self, M, n):
i = 0
While M! = N:
M >>= 1
n >>= 1
i + = 1
return n << I
------
TestCase:
"4,7"
4:0x0100
5:0x0101
6:0x0110
7:0x0111
Can be done with a while loop, but the efficiency is too low, there is a very good algorithm, from Leetcode School, explained:
Assuming that the two digits of the tail are m=0bxyz0xxx,n=0bxyz1xxx,
Wherein, that is, the decomposition of a number, the first part is a high two digits of the common part, and the other part of the low two number difference of the part:
At this point, the result value is divided into two parts: the high is two digits high public part, the low is all 0.
Well, why is that so? Because the two values of the low two number differences in the part must be found 0!
This point is a turning point, but also ushered in the climax of the algorithm. That is to say , in successive integers, each bit of a low-level different part must exist in an integer of 0 in the meantime .
0x01111111
0x10000000
This conclusion is not a direct thought, but can be used to disprove the thinking, if you cannot find such a 0, then the continuous integer sequence is this:
0bxyz***1***
0bxyx***1***
0bxyz***1***
0bxyz***1***
obxyz***1***
That string of 1, like a wall, blocks the rounding of successive integers, which limits the number of consecutive integers.
When 1 strings are in No. 0 place, the number of consecutive integers is up to 1
When 1 strings are in 1th place, the number of consecutive integers is up to 2
When 1 strings are in 2nd place, the number of consecutive integers is up to 4
Python algorithm: Rangebitwiseand (with consecutive integers)