Skip to content

Latest commit

 

History

History
143 lines (104 loc) · 2.67 KB

File metadata and controls

143 lines (104 loc) · 2.67 KB

English Version

题目描述

给你两个整数 leftright ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 leftright 端点)。

 

示例 1:

输入:left = 5, right = 7
输出:4

示例 2:

输入:left = 0, right = 0
输出:0

示例 3:

输入:left = 1, right = 2147483647
输出:0

 

提示:

  • 0 <= left <= right <= 231 - 1

解法

方法一:位运算

题目可以转换为求数字的公共二进制前缀。

$left \lt right$ 时,我们循环将 $right$ 的最后一个二进制位 $1$ 变成 $0$,直到 $left = right$,此时 $right$ 即为数字的公共二进制前缀,返回 $right$ 即可。

时间复杂度 $O(\log n)$,空间复杂度 $O(1)$

Python3

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

Java

class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
}

C++

class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
};

Go

func rangeBitwiseAnd(left int, right int) int {
	for left < right {
		right &= (right - 1)
	}
	return right
}

C#

public class Solution {
    public int RangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
}

JavaScript

/**
 * @param {number} left
 * @param {number} right
 * @return {number}
 */
var rangeBitwiseAnd = function (left, right) {
    while (left < right) {
        right &= right - 1;
    }
    return right;
};

...