Integer Replacement

Given a positive integer n, return the minimum number of replacements needed to reduce n to 1. Pattern focus: Isolate Lowest Bit. Odd numbers must be nudged using +1 or -1 based on low-bit structure, while even numbers are shifted right.

Input Format

n = positive integer

Output Format

minimum number of replacements to reduce n to 1

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • n must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

n = 8

Output:

3

Explanation:

8 -> 4 -> 2 -> 1 takes three steps.

Example 2:

Input:

n = 7

Output:

4

Explanation:

One optimal path is 7 -> 8 -> 4 -> 2 -> 1.

Loading...
Integer Replacement - Bit Manipulation