LeetCode 题解工作台

数字范围按位与

给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、 right 端点)。 示例 1: 输入: left = 5, right = 7 输出: 4 示例 2: 输入: left = 0, right = 0 输出:…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 位运算·操作·driven·solution·strategy

bolt

答案摘要

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

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

解题思路

方法一:位运算

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

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

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

1
2
3
4
5
6
class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        while left < right:
            right &= right - 1
        return right
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They want you to notice that iterating from left to right is the wrong model once the interval gets large.

  • question_mark

    They expect you to explain why differing lower bits vanish, not just recite a shift loop.

  • question_mark

    A strong answer connects the final value to the common binary prefix of left and right.

warning

常见陷阱

外企场景
  • error

    Looping through every number in the range times out conceptually and misses the actual Bit Manipulation pattern.

  • error

    Assuming the AND depends only on left & right ignores intermediate values that zero out extra bits.

  • error

    Forgetting that once the range crosses a power-of-two boundary, many lower bits immediately become unstable and drop to 0.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the common binary prefix length instead of the final AND value.

  • arrow_right_alt

    Handle many range AND queries, where preprocessing or trie-like bit grouping may become relevant.

  • arrow_right_alt

    Generalize the reasoning to explain why range OR keeps unstable bits as 1 instead of 0.

help

常见问题

外企场景

数字范围按位与题解:位运算·操作·driven·solution·… | LeetCode #201 中等