> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Integer Replacement Python Solution with Tests

> Tested Python solution for LeetCode 397 with 22 pytest cases. Generate a practice environment with lcpy.

LeetCode 397, [Medium](/catalog/medium). Topics: [Dynamic Programming](/catalog/topics/dynamic-programming), [Greedy](/catalog/topics/greedy), [Bit Manipulation](/catalog/topics/bit-manipulation), [Memoization](/catalog/topics/memoization). [View on LeetCode](https://leetcode.com/problems/integer-replacement/description/).

Generate this problem as a practice environment: tested reference solution, 22 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 397   # by problem number
lcpy gen -s integer_replacement   # by problem name
```

## Problem

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`.

### Examples

```
Input: n = 8
Output: 3
Explanation: 8 -> 4 -> 2 -> 1
```

```
Input: n = 7
Output: 4
Explanation: 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
```

```
Input: n = 4
Output: 2
```

### Constraints

* 1 \<= n \<= 2^31 - 1

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/integer_replacement/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/integer_replacement/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(log n)
    # Space: O(log n)
    def integer_replacement(self, n: int) -> int:
        ops = 0
        while n != 1:
            if n % 2 == 0:
                n //= 2
            elif n == 3 or n % 4 == 1:
                n -= 1
            else:
                n += 1
            ops += 1
        return ops
```

## Complexity

| Time | Space |
| - | - |
| O(log n) | O(log n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.