Integer Replacement

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.

Example 1
Inputn = 8
Output3
Starting from 8, the sequence 8 -> 4 -> 2 -> 1 takes 3 operations.
Example 2
Inputn = 7
Output4
Starting from 7, either 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1 takes 4 operations.

Constraints

  • 1 <= n <= 2^31 - 1

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate