Minimum Operations to Make the Integer Zero - Problem

You are given two integers num1 and num2.

In one operation, you can choose integer i in the range [0, 60] and subtract 2i + num2 from num1.

Return the integer denoting the minimum number of operations needed to make num1 equal to 0.

If it is impossible to make num1 equal to 0, return -1.

Input & Output

Example 1 — Basic Case
$ Input: num1 = 11, num2 = 1
Output: 3
💡 Note: We need 3 operations: 11 - (2³ + 1) - (2⁰ + 1) - (2⁰ + 1) = 11 - 9 - 2 - 2 = 0. So we subtract (8+1), (1+1), (1+1) in 3 operations.
Example 2 — Impossible Case
$ Input: num1 = 1, num2 = -7
Output: -1
💡 Note: Each operation adds to num1 (since we subtract negative num2), making it impossible to reach 0 from positive num1.
Example 3 — Single Operation
$ Input: num1 = 3, num2 = 2
Output: 1
💡 Note: One operation: 3 - (2⁰ + 2) = 3 - 3 = 0. We subtract (1+2) in 1 operation.

Constraints

  • 1 ≤ num1 ≤ 109
  • -109 ≤ num2 ≤ 109

Visualization

Tap to expand
Minimum Operations: num1=11, num2=1 → 011Initial-(2³+1) = -92After op 1-(2⁰+1) = -20Final3 operations needed: 11 - 9 - 2 = 0Answer: 3
Understanding the Visualization
1
Input
num1=11, num2=1 - need to make num1 zero
2
Operations
Each operation subtracts 2^i + num2 for some i ∈ [0,60]
3
Solution
Find minimum operations needed, or -1 if impossible
Key Takeaway
🎯 Key Insight: Transform the problem into finding k such that (num1 - k*num2) can be expressed as sum of exactly k powers of 2
Asked in
Microsoft 15 Google 12
18.5K Views
Medium Frequency
~25 min Avg. Time
423 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen