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: 8 Output: 3 Explanation: 8 -> 4 -> 2 -> 1
Example 2:
Input: 7 Output: 4 Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1
Subscribe to see which companies asked this question
最近好几个都是math相关的
首先是手动算几个,看看能不能找到什么规律
发现,每次手动算都会倾向于得到正确的结果,那么就看看自己脑袋里是怎么决定的
关键点很好找,在与到底应该加一还是减一
发现是这样的,每次判断+1 -1的时候,看得到的结果包含的2因子是否更多,所以用一个calTwo函数计算2 作为因子的个数,取多的
就过了
class Solution(object):
def calTwo(self,n):
res = 0
while n > 0:
if n % 2 ==0:
n /= 2
res += 1
else:
break
return res
def integerReplacement(self, n):
res = 0
while n > 1:
#print n
if n == 3:
return res + 2
if n % 2 == 0:
res += 1
n /= 2
else:
plus = self.calTwo(n+1)
minus = self.calTwo(n-1)
if plus > minus:
n += 1
else:
n -= 1
res += 1
return res