Given a positive integer n, you need to find the minimum number of operations to transform it into 1 using the following rules:

  • If n is even: replace n with n / 2
  • If n is odd: replace n with either n + 1 or n - 1

The challenge lies in making the optimal choice when n is odd. Should you add 1 or subtract 1? The goal is to reach 1 in the fewest steps possible.

Example: For n = 8: 8 → 4 → 2 → 1 (3 operations)
For n = 7: 7 → 6 → 3 → 2 → 1 (4 operations) vs 7 → 8 → 4 → 2 → 1 (4 operations)

Input & Output

example_1.py — Python
$ Input: n = 8
Output: 3
💡 Note: 8 → 4 → 2 → 1. Since 8 is even, we divide by 2 repeatedly until we reach 1. Total steps: 3.
example_2.py — Python
$ Input: n = 7
Output: 4
💡 Note: 7 → 6 → 3 → 2 → 1 (4 steps) or 7 → 8 → 4 → 2 → 1 (4 steps). Both paths take 4 operations, but the first is found by our optimal strategy.
example_3.py — Python
$ Input: n = 4
Output: 2
💡 Note: 4 → 2 → 1. Since 4 is even, we can divide by 2 twice. Total steps: 2.

Constraints

  • 1 ≤ n ≤ 231 - 1
  • n is a positive integer
  • The answer is guaranteed to fit in a 32-bit integer

Visualization

Tap to expand
1n/4n/2n÷2 or ±1→÷2÷2÷2🏔️ Mountain Descent StrategyEven heights: Express elevator (÷2)Odd heights: Walk ±1 to reach elevator⚡ Bit Manipulation InsightOdd ending in '11' → +1 (creates trailing zeros)Odd ending in '01' → -1 (eliminates 1-bit)Special case: 3 → 2 (always subtract)Goal: Maximize consecutive divisions by 2
Understanding the Visualization
1
Start at height n
Begin your descent from the initial number
2
Even heights: Take elevator
When n is even, divide by 2 (fastest descent)
3
Odd heights: Choose wisely
When n is odd, pick +1 or -1 to set up better elevator opportunities
4
Bit pattern strategy
Use binary patterns: '11' ending → +1, '01' ending → -1
5
Reach base camp
Continue until you reach height 1
Key Takeaway
🎯 Key Insight: The optimal strategy treats this as a bit manipulation problem where we aim to create the maximum number of trailing zeros, allowing for more efficient consecutive divisions by 2.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
42.0K Views
Medium-High Frequency
~18 min Avg. Time
1.6K 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