You are given a positive integer n. In one operation you change n as follows:
-
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.
Function Signature
def integer_replacement(n: int) -> int:
Rules
-
An even value has exactly one move, halving. A choice exists only when the value is odd.
-
If
n
is already
1
, the answer is
0
.
-
Intermediate values may be larger than the starting
n
(for example,
n + 1
when
n = 2^31 - 1
).
Constraints
Examples
Input: n = 8
Output: 3
8 is a power of two, so every move is a halving: 8 -> 4 -> 2 -> 1 takes three operations.
Input: n = 7
Output: 4
Both 7 -> 8 -> 4 -> 2 -> 1 and 7 -> 6 -> 3 -> 2 -> 1 take four operations. After three operations the only reachable values are 2 and 4, so no shorter sequence exists.
Input: n = 15
Output: 5
15 -> 16 -> 8 -> 4 -> 2 -> 1 takes five operations. Starting with 15 -> 14 -> 7 costs two operations and leaves 7, which needs four more, for six in total.