201. Bitwise AND of Numbers Range

https://leetcode.com/problems/bitwise-and-of-numbers-range/

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

Example 1:

Input: [5,7]
Output: 4

Example 2:

Input: [0,1]
Output: 0

问[m, n]范围内所有整数做位相与的结果。相与只要该位有0对应结果就是0。因此只有从左边开始m和n相同的位才能确保[m, n]内所有数对应位上是1的相与还会是1。不断右移,当m==n时意味着已经移到共有的位上了,停止并把这些位放回原来的位置即结果。

class Solution:
    def rangeBitwiseAnd(self, m: int, n: int) -> int:
        r = 0
        while m < n:
            m >>= 1
            n >>= 1
            r += 1
        return m << r

Last updated