Integer Replacement - Problem
Given a positive integer n, you can apply one of the following operations:
- If
nis even, replacenwithn / 2 - If
nis odd, replacenwith eithern + 1orn - 1
Return the minimum number of operations needed for n to become 1.
Input & Output
Example 1 — Basic Case
$
Input:
n = 8
›
Output:
3
💡 Note:
8 is even → 8/2 = 4, then 4/2 = 2, then 2/2 = 1. Total: 3 operations.
Example 2 — Odd Number Choice
$
Input:
n = 7
›
Output:
4
💡 Note:
7 is odd → choose 7-1=6, then 6/2=3, then 3-1=2, then 2/2=1. Total: 4 operations.
Example 3 — Small Odd
$
Input:
n = 3
›
Output:
2
💡 Note:
3 is odd → choose 3-1=2 (better than 3+1=4), then 2/2=1. Total: 2 operations.
Constraints
- 1 ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Start with positive integer n
2
Process
Apply operations: divide by 2 if even, add/subtract 1 if odd
3
Output
Return minimum operations to reach 1
Key Takeaway
🎯 Key Insight: Use bit patterns to choose optimal operations - add 1 when odd numbers end with '11' in binary to create more trailing zeros
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code