Topic links: https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/
Subject description:
Given the range of [m, n], where 0 <= m <= n <= 2147483647, returns all numbers in this range with a bitwise (containing m, n both inclusive).
Example:
Example 1:
输入: [5,7]
输出: 4
Example 2:
输入: [0,1]
输出: 0
Ideas:
Because as long as one 0
, regardless of how many 1
are0
For example: from 5
to7
5:0 1 0 1
6:0 1 1 0
7:0 1 1 1
-----------
0 1 0 0
Therefore, code is as follows:
class Solution:
def rangeBitwiseAnd(self, m: int, n: int) -> int:
i = 0
while m != n:
m >>= 1
n >>= 1
i += 1
return m << i