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 Integer to 0 INPUT n = 39 in binary: 1 32 0 16 0 8 1 4 1 2 1 1 100111 = 39 39 = 32 + 4 + 2 + 1 = 2^5 + 2^2 + 2^1 + 2^0 n = 39 Input: n = 39 GREEDY ALGORITHM 1 Consecutive 1s 111 at end (bits 0-2) Add 2^0=1: 39+1=40 2 Result: 40 40 = 101000 binary Single 1 at bit 3 3 Subtract 8 40 - 8 = 32 32 = 100000 binary 4 Subtract 32 32 - 32 = 0 Done! n = 0 Operations: 1. 39 + 1 = 40 2. 40 - 8 = 32 3. 32 - 32 = 0 FINAL RESULT Path to Zero: 39 +1 40 -8 32 -32 0 Output: 3 Key Insight: For consecutive 1s in binary: adding 1 converts them to a single 1 (e.g., 111 + 1 = 1000). Greedy approach: If 3+ consecutive 1s, add power of 2. Otherwise, subtract the lowest set bit. This minimizes operations by reducing multiple bits at once instead of handling them individually. TutorialsPoint - Minimum Operations to Reduce an Integer to 0 | Greedy Approach
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