Minimum Operations to Reduce an Integer to 0 - 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.

A number x is power of 2 if x == 2i where i >= 0.

Input & Output

Example 1 — Medium Number
$ Input: n = 39
Output: 3
💡 Note: 39 in binary is 100111. We can do: 39 + 1 = 40 (1 op), 40 - 8 = 32 (2 ops), 32 - 32 = 0 (3 ops). Total: 3 operations.
Example 2 — Power of 2
$ Input: n = 8
Output: 1
💡 Note: 8 is a power of 2 (2³), so we can subtract 8 directly: 8 - 8 = 0. Only 1 operation needed.
Example 3 — Small Number
$ Input: n = 3
Output: 2
💡 Note: 3 in binary is 11. We can do: 3 + 1 = 4 (1 op), then 4 - 4 = 0 (2 ops). Or: 3 - 2 = 1 (1 op), 1 - 1 = 0 (2 ops). Both take 2 operations.

Constraints

  • 1 ≤ n ≤ 106

Visualization

Tap to expand
Minimum Operations to Reduce 39 to 0n = 39Starting number+1+2+4-1-2-4Available Operations(Powers of 2)Optimal Solution:Step 1: 39 + 1 = 40Step 2: 40 - 8 = 32Step 3: 32 - 32 = 0Minimum Operations:3
Understanding the Visualization
1
Input
Given positive integer n = 39
2
Operations
Can add or subtract powers of 2: ±1, ±2, ±4, ±8, ±16, ±32...
3
Goal
Find minimum operations to make n = 0
Key Takeaway
🎯 Key Insight: Use bit manipulation to handle consecutive 1s efficiently by adding rather than subtracting multiple powers of 2
Asked in
Google 25 Facebook 18 Amazon 15
23.5K Views
Medium Frequency
~15 min Avg. Time
890 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