LeetCode-Python-201. 数字范围按位与

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

示例 1: 

输入: [5,7]
输出: 4
示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bitwise-and-of-numbers-range
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

第一种思路:

暴力模拟法。

class Solution(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        while n > m:
            n &= n - 1
        return n

第二种思路:

递归处理,

如果m!=n,则因为相邻两数 & 结果 必定为0,可以递归处理,

当前结果 = 递归结果 + 末尾一个0

class Solution(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        if m == 0 or m == n:
            return m
        else: #当n > m的时候,因为相邻两个数 &的结果的最后一位必定为0,因此可以递归处理
            return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1

 

你可能感兴趣的:(Leetcode,Python)