LeetCode 题解工作台

将整数减少到零需要的最少操作数

给你一个正整数 n ,你可以执行下述操作 任意 次: n 加上或减去 2 的某个 幂 返回使 n 等于 0 需要执行的 最少 操作数。 如果 x == 2 i 且其中 i >= 0 ,则数字 x 是 2 的幂。 示例 1: 输入: n = 39 输出: 3 解释: 我们可以执行下述操作: - n 加…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

bolt

答案摘要

我们将整数 转换为二进制,从最低位开始: - 如果当前位为 ,我们就累加当前连续的 的个数;

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n ,你可以执行下述操作 任意 次:

  • n 加上或减去 2 的某个

返回使 n 等于 0 需要执行的 最少 操作数。

如果 x == 2i 且其中 i >= 0 ,则数字 x2 的幂。

 

示例 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
lightbulb

解题思路

方法一:贪心 + 位运算

我们将整数 nn 转换为二进制,从最低位开始:

  • 如果当前位为 11,我们就累加当前连续的 11 的个数;
  • 如果当前位为 00,我们就判断当前连续的 11 的个数是否超过 00。如果是,判断当前连续的 11 的个数是否为 11,如果是,说明我们通过一次操作可以消除 11;如果大于 11,说明我们通过一次操作,可以把连续的 11 的个数减少到 11

最后,我们还需要判断当前连续的 11 的个数是否为 11,如果是,说明我们通过一次操作可以消除 11;如果大于 11,我们通过两次操作,可以把连续的 11 的消除。

时间复杂度 O(logn)O(\log n),空间复杂度 O(1)O(1)。其中 nn 为题目给定的整数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

将整数减少到零需要的最少操作数题解:状态·转移·动态规划 | LeetCode #2571 中等