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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code