It has to be said that the application of bit arithmetic is very ingenious.
This problem asks for a continuous interval integer and the value of the operation, the breakout point lies in the continuous interval of this feature. We can find a few numbers to see the rules,
2 3 4 5 binary is 10, 11,100,101, can be found if m==n, then M is the answer; when M!=n, because of the continuous two number of binary
The last one is certainly not the same, with the value must be 0, the previous same section (1&1=1,0&0=0) remains.
So each time we first judge, different words will move right one, compare the previous, until the same time end, the last left to move the number of digits.
There is no need to worry about 1 of the time left shift will cause overflow, and thus fail, because the right shift is preceded by 0.
Class Solution {public: int rangebitwiseand (int m, int n) { int res = 0; int offset = 0; while (m!=n) { m>>=1; n>>=1; offset++; } Return m<<offset; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode] Bitwise and of Numbers Range (bitwise operations)