LeetCode 题解工作台
仅含置位位的最小整数
给你一个正整数 n 。 返回 大于等于 n 且二进制表示仅包含 置位 位的 最小 整数 x 。 置位 位指的是二进制表示中值为 1 的位。 示例 1: 输入: n = 5 输出: 7 解释: 7 的二进制表示是 "111" 。 示例 2: 输入: n = 10 输出: 15 解释: 15 的二进制表…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数学·位运算
答案摘要
我们从 $x = 1$ 开始,不断将 左移,直到 $x - 1 \geq n$,此时 $x - 1$ 就是我们要找的答案。 时间复杂度 $O(\log n)$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路
题目描述
给你一个正整数 n。
返回 大于等于 n 且二进制表示仅包含 置位 位的 最小 整数 x 。
置位 位指的是二进制表示中值为 1 的位。
示例 1:
输入: n = 5
输出: 7
解释:
7 的二进制表示是 "111"。
示例 2:
输入: n = 10
输出: 15
解释:
15 的二进制表示是 "1111"。
示例 3:
输入: n = 3
输出: 3
解释:
3 的二进制表示是 "11"。
提示:
1 <= n <= 1000
解题思路
方法一:位运算
我们从 开始,不断将 左移,直到 ,此时 就是我们要找的答案。
时间复杂度 ,空间复杂度 。
class Solution:
def smallestNumber(self, n: int) -> int:
x = 1
while x - 1 < n:
x <<= 1
return x - 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands the concept of powers of two and bit manipulation.
- question_mark
Candidate applies bit manipulation to efficiently compute the answer.
- question_mark
Candidate avoids brute force approaches and seeks optimized solutions.
常见陷阱
外企场景- error
Misunderstanding the binary representation of numbers with all set bits.
- error
Using inefficient or brute force methods to calculate the result.
- error
Overcomplicating the problem and missing simple bitwise solutions.
进阶变体
外企场景- arrow_right_alt
What if n is already a number with all set bits?
- arrow_right_alt
What if n is at the maximum limit (1000)?
- arrow_right_alt
What if n is a power of two, and no subtraction is needed?