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: 2
💡 Note: We need 2 operations: First, 11 - (2³ + 1) = 11 - 9 = 2. Then, 2 - (2⁰ + 1) = 2 - 2 = 0. The target after subtracting 2*num2 is 11-2*1=9, which can be expressed as sum of 2 powers of 2 (8+1).
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 to Make Integer Zero INPUT num1 = 11 num2 = 1 Binary of 11: 1 0 1 1 Each Operation: num1 -= (2^i + num2) where i in [0, 60] Power Range: 2^0=1 ... 2^60 ALGORITHM STEPS 1 Calculate Target target = num1 - k*num2 2 Check Bounds target >= k (min ops) 3 Count Set Bits popcount(target) <= k 4 Find Min k Iterate k from 1 to 60 Iteration (num2=1): k=1: 11-1=10, bits=2 >1 FAIL k=2: 11-2=9, bits=2 <=2 FAIL k=3: 11-3=8, bits=1 <=3 OK 8 = 2^3, valid decomposition! FINAL RESULT Output: 3 3 Operations Used: Op1: 11-(2^3+1)=2 Op2: 2-(2^0+1)=0 Op3: 0-(2^0+1)=-2 Alternative View: target=8=2^3 =2^2+2^1+2^0+2^0 3 powers sum to 8 Key Insight: Mathematical Bounds Optimization After k operations, we subtract k*num2, leaving target = num1 - k*num2. This target must be expressible as sum of exactly k powers of 2. This requires: (1) target >= k, and (2) popcount(target) <= k. We can split any 2^i into two 2^(i-1), so any sum with popcount(target) <= k can use exactly k terms. TutorialsPoint - Minimum Operations to Make the Integer Zero | Mathematical Bounds Optimization
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