LeetCode 题解工作台
使整数变为 0 的最少操作次数
给你一个整数 n ,你需要重复执行多次下述操作将其转换为 0 : 翻转 n 的二进制表示中最右侧位(第 0 位)。 如果二进制表示中的第 (i-1) 位为 1 且从第 (i-2) 位到第 0 位都为 0 ,则翻转 n 的二进制表示中的第 i 位。 返回将 n 转换为 0 的最小操作次数。 示例 1:…
3
题型
6
代码语言
3
相关题
当前训练重点
困难 · 状态·转移·动态规划
答案摘要
本题实际上求的是格雷码为 的逆变换,即通过格雷码构造原数。 我们先来回顾一下二进制码转换成二进制格雷码,其法则是保留二进制码的最高位作为格雷码的最高位,而次高位格雷码为二进制码的高位与次高位相异或,而格雷码其余各位与次高位的求法相类似。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数 n,你需要重复执行多次下述操作将其转换为 0 :
- 翻转
n的二进制表示中最右侧位(第0位)。 - 如果二进制表示中的第
(i-1)位为1且从第(i-2)位到第0位都为0,则翻转n的二进制表示中的第i位。
返回将 n 转换为 0 的最小操作次数。
示例 1:
输入:n = 3 输出:2 解释:3 的二进制表示为 "11" "11" -> "01" ,执行的是第 2 种操作,因为第 0 位为 1 。 "01" -> "00" ,执行的是第 1 种操作。
示例 2:
输入:n = 6 输出:4 解释:6 的二进制表示为 "110". "110" -> "010" ,执行的是第 2 种操作,因为第 1 位为 1 ,第 0 到 0 位为 0 。 "010" -> "011" ,执行的是第 1 种操作。 "011" -> "001" ,执行的是第 2 种操作,因为第 0 位为 1 。 "001" -> "000" ,执行的是第 1 种操作。
提示:
0 <= n <= 109
解题思路
方法一:格雷码逆变换(格雷码转二进制码)
本题实际上求的是格雷码为 的逆变换,即通过格雷码构造原数。
我们先来回顾一下二进制码转换成二进制格雷码,其法则是保留二进制码的最高位作为格雷码的最高位,而次高位格雷码为二进制码的高位与次高位相异或,而格雷码其余各位与次高位的求法相类似。
假设某个二进制数表示为 ,其格雷码表示为 。最高位保留,所以 ;而其它各位 ,其中 。
那么,格雷码转换成二进制码的逆变换是什么呢?
我们可以发现,格雷码的最高位保留,所以 ;而 ;而其它各位 ,其中 。因此,我们可以用下面的函数 得到其二进制码:
int rev(int x) {
int n = 0;
for (; x != 0; x >>= 1) {
n ^= x;
}
return n;
}
时间复杂度 ,其中 为题目给定的整数。空间复杂度 。
class Solution:
def minimumOneBitOperations(self, n: int) -> int:
ans = 0
while n:
ans ^= n
n >>= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(log n) because each bit in n contributes to a state computation. Space complexity is O(1) for the iterative solution or O(log n) for recursive memoization, as only one value per bit needs storage, avoiding full DP tables. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Can you model the problem as a recursive state transition?
- question_mark
Are you recognizing how higher-order bits affect operation counts?
- question_mark
Have you optimized using memoization to prevent redundant bit calculations?
常见陷阱
外企场景- error
Ignoring the dependency of a bit on all lower bits causes overcounting operations.
- error
Attempting a greedy left-to-right flip without tracking state may fail on examples like n = 6.
- error
Failing to memoize recursive computations leads to exponential time and timeouts.
进阶变体
外企场景- arrow_right_alt
Compute minimum operations for multiple integers in a batch.
- arrow_right_alt
Modify the rule to allow flipping only contiguous sequences of bits and find minimal flips.
- arrow_right_alt
Find the total sequence of bit positions flipped, not just the count.