Given a positive integer n, you can apply one of the following operations:

  • If n is even, replace n with n / 2
  • If n is odd, replace n with either n + 1 or n - 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
Integer Replacement: Find Minimum Path to 1Inputn = 15OperationsEven: n ÷ 2Odd: n±115168421+1÷2÷2÷2÷2Output5 operationsPath: 15 → 16 → 8 → 4 → 2 → 1
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
Asked in
Google 25 Microsoft 18 Facebook 15 Amazon 12
28.4K Views
Medium Frequency
~15 min Avg. Time
856 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