其他分享
首页 > 其他分享> > [LeetCode] 201. 数字范围按位与

[LeetCode] 201. 数字范围按位与

作者:互联网

题目链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range/

题目描述:

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

示例:

示例 1:

输入: [5,7]
输出: 4

示例 2:

输入: [0,1]
输出: 0

思路:

因为 只要有一个0,那么无论有多少个 1都是 0

比如:从 57

5:0 1 0 1
6:0 1 1 0
7:0 1 1 1
-----------
  0 1 0 0

所以,代码如下:

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

标签:201,输出,题目,示例,int,bitwise,按位,LeetCode,输入
来源: https://www.cnblogs.com/powercai/p/11370280.html