LeetCode 201 Bitwise AND of Numbers Range (Python)

Posted by 小明MaxMing on April 26, 2020

题目

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

解题思路

先把m和n转换成2进制,如果长度不同,则结果为0

找出m和n的公共前缀,后面变成0,就是最后的结果

代码

class Solution:
    def rangeBitwiseAnd(self, m: int, n: int) -> int:
        if len(bin(m)) != len(bin(n)):
            return 0
        res = 0
        while (m != n):
            m >>= 1
            n >>= 1
            res += 1
        return m << res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅