[LeetCode] 201. numerical range bitwise AND

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 1are0

For example: from 5to7

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

Guess you like

Origin www.cnblogs.com/powercai/p/11370280.html