LeetCode solutions

2837. Minimum Operations to Make the Integer Zero

My accepted Python solution to LeetCode problem 2837, Minimum Operations to Make the Integer Zero, running in 0ms.

  • Difficulty: Medium
  • Python
  • Runtime 0ms
  • Memory 17.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.3MB, accepted 2026-01-01.

python
class Solution:
    def makeTheIntegerZero(self, num1: int, num2: int) -> int:
        # After k operations: num1 - k*num2 - (sum of 2^i)
        # We need: num1 - k*num2 = sum of k powers of 2
        # The number of set bits in target must be <= k
        # And target must be >= k (each 2^i >= 1)
        
        for k in range(61):  # At most 60 operations
            target = num1 - k * num2
            if target < 0:
                break
            if target < k:
                continue
            # Count bits in target
            bits = bin(target).count('1')
            # We can form target with k numbers if bits <= k <= target
            if bits <= k <= target:
                return k
        
        return -1

Source