Minimum Operations to Reduce an Integer to 0 Problem
Description
LeetCode Problem 2571.
You are given a positive integer n, you can do the following operation any number of times:
- Add or subtract a power of
2fromn.
Return the minimum number of operations to make n equal to 0.
A number x is power of 2 if x == 2^i where i >= 0.
Example 1:
Input: n = 39
Output: 3
Explanation: We can do the following operations:
- Add 2^0 = 1 to n, so now n = 40.
- Subtract 2^3 = 8 from n, so now n = 32.
- Subtract 2^5 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
Example 2:
Input: n = 54
Output: 3
Explanation: We can do the following operations:
- Add 2^1 = 2 to n, so now n = 56.
- Add 2^3 = 8 to n, so now n = 64.
- Subtract 2^6 = 64 from n, so now n = 0.
So the minimum number of operations is 3.
Constraints:
1 <= n <= 10^5
Solution
Approach: Greedy on Bits
Scan the bits of n from the lowest. A run of consecutive 1s can be removed in two operations (add the lowest 1 of the run to turn it into a 1 one place higher, then subtract it), except a run of a single 1, which costs one operation.
Keep the length of the current run cnt. At a 0 bit that ends a run: a single 1 costs one operation and clears the run; a longer run costs one operation and leaves a single 1 carried into the next bit. When the bits run out, a leftover single 1 costs one more operation and a longer run costs two.
Complexity: time O(log n), space O(1), where n is the given integer.
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