Problem
Given a positive integern, you can apply one of the following operations:
- If
nis even, replacenwithn / 2. - If
nis odd, replacenwith eithern + 1orn - 1.
n to become 1.
Examples
Constraints
- 1 <= n <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 397 with 22 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 397 # by problem number
lcpy gen -s integer_replacement # by problem name
n, you can apply one of the following operations:
n is even, replace n with n / 2.n is odd, replace n with either n + 1 or n - 1.n to become 1.
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
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
| Time | Space |
|---|---|
| O(log n) | O(log n) |