关于LeetCode中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 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

UPDATE:
We have fixed the error in Integer Replacement. For input n = 3, the answer should be 2, not 3. Please try submitting again, thanks. We will rejudge your submissions after the contest finished and adjust your ranking accordingly.

     题目就不解释了,通俗易懂。需要注意的问题就是输入为int类型最大值的时候,虽然输入限制为int类型,但是题干可没说所有中间过程都是在int的范围内的,所以中间环节是可能出现2147483648这个数字的,它正好等于int最大值加上1。

    这道题的主要思想其实是尽量减少-1和+1操作出现的次数,尽量多使用除2操作,这就要求中间环节的数字是偶数的次数多一些。所以,在每次进行+1或-1操作后我们会得到两个偶数。这时,我们就需要再对这个新的偶数进行一次除2操作,得到的数可能是奇数或者偶数(这取决于你之前选择的是+1操作还是-1操作,所以我们要都算一遍),我们最后会选择这个偶数进行下一次除2操作。已Accepted的代码如下所示:

    public int integerReplacement(int n) {
        int count = 0;
        while(n!=1){
            count++;
            if(n%2==0){
                n = n/2;
            }else{
                int temp1 = (n-1)/2;
                int temp2 = temp1+1;
                int temp = 0;
                if(temp1%2==0 || temp1==1){
                    temp = temp1;
                }else{
                    temp = temp2;
                }
                n = temp;
                count++;
            }
        }
        return count;
    }
    评论区地址在这里: https://discuss.leetcode.com/category/521/integer-replacement,里面有其他使用递归和位运算的回答。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值