MediumNo. 2571

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

Topics
Greedy, Bit Manipulation, Dynamic Programming
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

PythonSolution
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

Time
O(log n)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0397Integer ReplacementMedium
2708Maximum Strength of a GroupMedium
2572Count the Number of Square-Free SubsetsMedium
2573Find the String with LCPHard
0044Wildcard MatchingHard
0045Jump Game IIMedium

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.

Free to download. Check it runs on your machine, then pick a plan.