Minimum Operations to Reduce an Integer to 0 — LeetCode 2571 Python Solution
- Problem
- #2571
- Pattern
- Bit Manipulation
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a positive integer n, you can do the following operation any number of times: Add or subtract a power of 2 from n. Return the minimum number of operations to make n equal to 0.
Example
- Input
- n = 39
- Output
- 3
- Explanation
- We can do the following operations:
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2571. Minimum Operations to Reduce an Integer to 0 is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2571. Minimum Operations to Reduce an Integer to 0?
- LeetCode 2571. Minimum Operations to Reduce an Integer to 0 is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2571. Minimum Operations to Reduce an Integer to 0?
- The Python solution on this page runs in O(\log n).
- What is the space complexity of LeetCode 2571. Minimum Operations to Reduce an Integer to 0?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2571. Minimum Operations to Reduce an Integer to 0 cover?
- LeetCode 2571. Minimum Operations to Reduce an Integer to 0 is tagged Greedy, Bit Manipulation and Dynamic Programming on LeetCode.