LeetCode 题解工作台
将整数减少到零需要的最少操作数
给你一个正整数 n ,你可以执行下述操作 任意 次: n 加上或减去 2 的某个 幂 返回使 n 等于 0 需要执行的 最少 操作数。 如果 x == 2 i 且其中 i >= 0 ,则数字 x 是 2 的幂。 示例 1: 输入: n = 39 输出: 3 解释: 我们可以执行下述操作: - n 加…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们将整数 转换为二进制,从最低位开始: - 如果当前位为 ,我们就累加当前连续的 的个数;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个正整数 n ,你可以执行下述操作 任意 次:
n加上或减去2的某个 幂
返回使 n 等于 0 需要执行的 最少 操作数。
如果 x == 2i 且其中 i >= 0 ,则数字 x 是 2 的幂。
示例 1:
输入:n = 39 输出:3 解释:我们可以执行下述操作: - n 加上 20 = 1 ,得到 n = 40 。 - n 减去 23 = 8 ,得到 n = 32 。 - n 减去 25 = 32 ,得到 n = 0 。 可以证明使 n 等于 0 需要执行的最少操作数是 3 。
示例 2:
输入:n = 54 输出:3 解释:我们可以执行下述操作: - n 加上 21 = 2 ,得到 n = 56 。 - n 加上 23 = 8 ,得到 n = 64 。 - n 减去 26 = 64 ,得到 n = 0 。 使 n 等于 0 需要执行的最少操作数是 3 。
提示:
1 <= n <= 105
解题思路
方法一:贪心 + 位运算
我们将整数 转换为二进制,从最低位开始:
- 如果当前位为 ,我们就累加当前连续的 的个数;
- 如果当前位为 ,我们就判断当前连续的 的个数是否超过 。如果是,判断当前连续的 的个数是否为 ,如果是,说明我们通过一次操作可以消除 ;如果大于 ,说明我们通过一次操作,可以把连续的 的个数减少到 。
最后,我们还需要判断当前连续的 的个数是否为 ,如果是,说明我们通过一次操作可以消除 ;如果大于 ,我们通过两次操作,可以把连续的 的消除。
时间复杂度 ,空间复杂度 。其中 为题目给定的整数。
class Solution:
def minOperations(self, n: int) -> int:
ans = cnt = 0
while n:
if n & 1:
cnt += 1
elif cnt:
ans += 1
cnt = 0 if cnt == 1 else 1
n >>= 1
if cnt == 1:
ans += 1
elif cnt > 1:
ans += 2
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the chosen approach; naive BFS can be O(n log n) due to powers of two exploration, while optimized DP with bit manipulation reduces redundant states. Space complexity is dominated by the number of states tracked in DP. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
They may hint at using binary representation to simplify operations.
- question_mark
Expect discussion of state transition or dynamic programming strategy.
- question_mark
Watch for opportunities to combine greedy bit-level optimization with DP.
常见陷阱
外企场景- error
Attempting only subtraction without considering additions of powers of two.
- error
Not limiting state expansion leads to excessive memory usage.
- error
Ignoring the benefit of flipping higher-order bits for faster reduction.
进阶变体
外企场景- arrow_right_alt
Minimize operations when only subtraction of powers of two is allowed.
- arrow_right_alt
Find maximum integer reachable within k operations of powers of two.
- arrow_right_alt
Count distinct sequences of operations that reduce n to zero.