201. Bitwise AND of Numbers Range

2020/11/08 leetcode 共 410 字,约 2 分钟

title

problem link Given a range [m, n] where 0

Example 1:

Input: [5,7] Output: 4

Example 2:

Input: [0,1] Output: 0

solution

本题中,我们需要得到m,n所有元素按位与的结果。举个例子,当m=26,n=30时,它们的二进制表示为为: 11010  11011  11100  11101  11110 这个样例的答案是11000,易见我们发现我们只需要找到m和n最左边的公共部分即可。

每次都将n与n-1按位与,当n的二进制为1010时,1010 & 1001 = 1000,相当于把二进制位的最后一个1去掉了。因此我们不断的做n^n-1的操作,直到n小于m相等即可。

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

Search

    Table of Contents