Minimum Operations to Reduce an Integer to 0 — LeetCode 2571 Python Solution

MediumGreedyBit ManipulationDynamic Programming
Problem
#2571
Reading time
3 min

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

Python
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

MeasureComplexity
TimeO(\log n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview