Minimum Operations to Reduce an Integer to 0 - Problem

You're given a positive integer n and need to reduce it to exactly 0 using the minimum number of operations.

In each operation, you can either:

  • Add a power of 2 to n
  • Subtract a power of 2 from n

A power of 2 is any number of the form 2^i where i โ‰ฅ 0 (i.e., 1, 2, 4, 8, 16, 32, ...).

Goal: Return the minimum number of operations needed to make n equal to 0.

Example: If n = 6, you could subtract 4 (2^2) to get 2, then subtract 2 (2^1) to get 0. That's 2 operations total.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 6
โ€บ Output: 3
๐Ÿ’ก Note: 6 in binary is 110. We can add 2 to get 8 (1000), then subtract 8 to get 0. Operations: +2, +1, -8 = 3 total operations.
example_2.py โ€” Power of 2
$ Input: n = 8
โ€บ Output: 1
๐Ÿ’ก Note: 8 is already a power of 2 (2^3), so we can subtract 8 in one operation to get 0.
example_3.py โ€” Small Number
$ Input: n = 1
โ€บ Output: 1
๐Ÿ’ก Note: We can subtract 1 (which is 2^0) in one operation to reach 0.

Visualization

Tap to expand
Optimal Strategy VisualizationExample: n = 54 (binary: 110110)12^512^402^312^212^102^0โ† Consecutive 1's hereStep 1: Add 2 to handle consecutive 1's at positions 1,254 + 2 = 56 (binary: 111000)Step 2: Add 8 to handle consecutive 1's at positions 3,4,556 + 8 = 64 (binary: 1000000)Step 3: Subtract 64 to reach 064 - 64 = 0Algorithm Decision Treeโ€ข Isolated 1: Subtract that power of 2โ€ข Consecutive 1s: Add smallest power to create carryโ€ข All 0s: Shift right (no operation needed)Why this works:Converting 111 โ†’ 1000 โ†’ subtract onceis better than subtracting 3 times individuallyTime: O(log n) | Space: O(1)Total operations for n=54: 3 steps
Understanding the Visualization
1
Analyze binary pattern
Look at the binary representation to identify consecutive 1's
2
Apply greedy strategy
For consecutive 1's, add to create carry; for isolated 1's, subtract
3
Optimize operations
Each decision reduces the problem size by eliminating bits efficiently
Key Takeaway
๐ŸŽฏ Key Insight: When binary representation has consecutive 1's, it's more efficient to add a small power of 2 to create a carry, then subtract the larger power of 2, rather than subtracting each 1 individually.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(log n)

We process each bit position at most once, and there are log n bit positions

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using a few variables regardless of input size

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค n โ‰ค 106
  • n is a positive integer
  • You can use any power of 2 (20, 21, 22, ...)
Asked in
Google 35 Meta 28 Microsoft 22 Amazon 18
24.6K Views
Medium Frequency
~15 min Avg. Time
945 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