Leetcode397: Integer Replacement

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:
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
题意:

给出一个数n,计算最少通过几步可以将这个n变成1。如果n是偶数,则n可以变成n/2;如果n是奇数,则n可以变成n-1或者n+1。

思路:

通过观察上面的例子很容易看出,如果n是2的幂的话,直接返回logn即可;如果不是的话,则按照题目的要求进行递归就行。

需要注意的是,有一个特殊的情况,就是2147483647的时候,2147483647+1不是int,直接运行会出现runtime  error。需要单独处理一下。

代码:

<span style="font-size:14px;">class Solution {
public:
    int integerReplacement(int n) {
        double num1=log10(n)/log10(2);
        int num2=(int)num1;
        if(num1==num2) return num2;
        if(n%2==0)
        return 1+integerReplacement(n/2);
        else{
            if(n==2147483647) 
            return 1+min(31, integerReplacement(n-1));
            return 1+min(integerReplacement(n+1), integerReplacement(n-1));
        }
    }
};</span>
后面我发现不求log,直接更直接地递归,好像快很多……

<span style="font-size:14px;">class Solution {
public:
    int integerReplacement(int n) {
        if(n==INT_MAX) return 32;
        if(n==1) return 0;
        if(n%2==0) return 1+integerReplacement(n/2);
        return 1+min(integerReplacement(n+1), integerReplacement(n-1));
    }
};</span>







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值