跳转至

201. 数字范围按位与

题目描述

给你两个整数 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)\)

1
2
3
4
5
class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        while left < right:
            right &= right - 1
        return right
1
2
3
4
5
6
7
8
class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
}
1
2
3
4
5
6
7
8
9
class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
};
1
2
3
4
5
6
func rangeBitwiseAnd(left int, right int) int {
    for left < right {
        right &= (right - 1)
    }
    return right
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/**
 * @param {number} left
 * @param {number} right
 * @return {number}
 */
var rangeBitwiseAnd = function (left, right) {
    while (left < right) {
        right &= right - 1;
    }
    return right;
};
1
2
3
4
5
6
7
8
public class Solution {
    public int RangeBitwiseAnd(int left, int right) {
        while (left < right) {
            right &= (right - 1);
        }
        return right;
    }
}

评论

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy