Analysis of leetcode notes in Bitwise AND of Numbers Range
I. Description
Given a range[m, n]
Where0 <= m <= n <= 2147483647
, Return the bitwise AND of all numbers in this range, inclusive.
For example, given the range[5, 7]
, You shoshould return4
.
Ii. Question Analysis
Given a range[m, n]
, Where0 <= m <= n <= 2147483647
Returns the bitwise AND of All integers in the range, including the boundary.m
Andn
. For example, if the specified range is[5, 7]
, Should return4
.
By looking at the description of the question, you can know that this question involves in-place operations. Therefore, you need to perform an analysis:
For the range [5, 7] given by the question, it can be written:
5: 1016: 110 -> 100 -> 47: 111
Here are two examples:
The value range is [6, 8]:
6: 01107: 0111 -> 0000 -> 08: 1000
The value range is [8, 10]:
8: 10009: 1001 -> 1000 -> 410: 1010
Now we can summarize the rule, for the range[m, n]
, Ifn
The highest effective bit ratiom
If the maximum valid bit of is high, there will inevitably be two numbers in the range, which are the reverse codes of the other Party:
6: 01107: 0111 -> 0000 -> 08: 1000
Therefore, only whenm
Andn
When the maximum valid bits are the same, that is, m and n are shifted right at the same time, andm == n,m == 1
When the bitwise AND result are not 0, the result ism
Andn
In the left-side header of the public, the following provides simple code:
Iii. Sample Code
class Solution {public: int rangeBitwiseAnd(int m, int n) { int bits = 0; while (m != n) { m >>= 1; n >>= 1; ++bits; } return m << bits; }};
Iv. Summary
This is a mathematical problem that can be quickly solved using bitwise operations, mainly to find out the law.