(LeetCode)Integer Replacement --- 整数替换

来源:互联网 发布:linux系统移植 pdf 编辑:程序博客网 时间:2024/05/21 09:23

Given a positive integer n and you can do operations as follow:

  1. If n is even, replace n with n/2.
  2. If n is odd, you can replace n with either n + 1 or n - 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 -> 1or7 -> 6 -> 3 -> 2 -> 1

Subscribe to see which companies asked this question


解题分析:

从题意中可以读出来,给出一个数字,怎么最快的把他变成1, 若是偶数,我们将他除以2,奇数的话我们 +1, -1就可以。

技巧:

可以利用递归方式,来依次缩小 n ,直到变成 1 为止。

# -*- coding:utf-8 --__author__ = 'jiuzhang'class Solution(object):    def integerReplacement(self, n):        if n == 1:            return 0        if n % 2 == 0:            return (1 + self.integerReplacement(n/2))        else:            return 2 + min(self.integerReplacement((n + 1)/2), self.integerReplacement((n - 1)/2))



0 0
原创粉丝点击