Skip to main content
  1. Posts/

LeetCode-397 整数替换

·1 min·

LeetCode-397 整数替换 #

Solution 1 #

递归.

代码如下:

class Solution:
    def integerReplacement(self, n: int) -> int:
        if n == 1:
            return 0
        if n & 1:
            return 1 + min(self.integerReplacement(n + 1), self.integerReplacement(n - 1))
        return 1 + self.integerReplacement(n // 2)