LeetCode 题解工作台
数字范围按位与
给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、 right 端点)。 示例 1: 输入: left = 5, right = 7 输出: 4 示例 2: 输入: left = 0, right = 0 输出:…
1
题型
6
代码语言
3
相关题
当前训练重点
中等 · 位运算·操作·driven·solution·strategy
答案摘要
题目可以转换为求数字的公共二进制前缀。 当 $left \lt right$ 时,我们循环将 的最后一个二进制位 变成 ,直到 $left = right$,此时 即为数字的公共二进制前缀,返回 即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路
题目描述
给你两个整数 left 和 right ,表示区间 [left, right] ,返回此区间内所有数字 按位与 的结果(包含 left 、right 端点)。
示例 1:
输入:left = 5, right = 7 输出:4
示例 2:
输入:left = 0, right = 0 输出:0
示例 3:
输入:left = 1, right = 2147483647 输出:0
提示:
0 <= left <= right <= 231 - 1
解题思路
方法一:位运算
题目可以转换为求数字的公共二进制前缀。
当 时,我们循环将 的最后一个二进制位 变成 ,直到 ,此时 即为数字的公共二进制前缀,返回 即可。
时间复杂度 ,空间复杂度 。
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
while left < right:
right &= right - 1
return right
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.