Leetcode练习(Python):位运算类:第201题:数字范围按位与:给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按

Posted 桌子哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode练习(Python):位运算类:第201题:数字范围按位与:给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按相关的知识,希望对你有一定的参考价值。

题目:

数字范围按位与:给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

思路:

因为是连续递增的数,可以通过移位来实现。

程序1:暴力大法,自然超时。

class Solution:
    def rangeBitwiseAnd(self, m: int, n: int) -> int:
        if m < 0 or m > 2147483647:
            return 
        if n < 0 or n > 2147483647:
            return 
        result = m
        for index in range(m, n + 1):
            result = result & index
        return result 

程序2:

class Solution:
    def rangeBitwiseAnd(self, m: int, n: int) -> int:
        if m < 0 or m > 2147483647:
            return 
        if n < 0 or n > 2147483647:
            return 
        auxiliary = 0
        while m < n:
            m = m >> 1
            n = n >> 1
            auxiliary += 1
        result = m << auxiliary
        return result

  

以上是关于Leetcode练习(Python):位运算类:第201题:数字范围按位与:给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按的主要内容,如果未能解决你的问题,请参考以下文章