题目描述:
LeetCode 397. Integer Replacement
Given a positive integer n and you can do operations as follow:
- If n is even, replace n with
n/2
. - If n is odd, you can replace n with either
n + 1
orn - 1
.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input: 8Output: 3Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: 7Output: 4Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
题目大意:
给定正整数n,你可以做如下操作:
如果n是偶数,将n替换为n/2
如果n是奇数,你可以将n替换为n + 1或者n - 1
求将n替换为1的最小次数
解题思路:
由于递归深度较小,因此直接根据题意递归求解即可
Python代码:
class Solution(object):
def integerReplacement(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1: return 0
if n & 1 == 0: return self.integerReplacement(n / 2) + 1
return min(self.integerReplacement(n + 1), self.integerReplacement(n - 1)) + 1