资讯专栏INFORMATION COLUMN

Leetcode 397. Integer Replacement

sutaking / 2689人阅读

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 or n - 1. What is the minimum number of replacements needed for n to become 1?

Example:

Input: 7

Output: 4

Explanation: 7 -> 8 -> 4 -> 2 -> 1 or 7 -> 6 -> 3 -> 2 -> 1

Tips: The infamous test with n=3 fails for that strategy because 11 ->10 -> 1 is better than 11 -> 100 -> 10 -> 1.

Solution:

If n is even, halve it.
If n=3 or n-1 has less 1"s than n+1,
decrement n. Otherwise, increment n.

Code:


public int integerReplacement(int n){
    int count = 0;
    while(n!= 1){
        if((n&1)==0){
            n>>>=1;
        }else if(n ==3 ||((n >>>1) & 1 ==0){
            --n;
        } else{
            ++n;
        }
        count++;
     }
    return count;

}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66429.html

相关文章

  • LeetCode[397] Integer Replacement

    摘要:复杂度思路利用位的操作。如果一个数是奇数,那么末位的位一定是。对于偶数,操作是直接除以。对于奇数的操作如果倒数第二位是,那么的操作比的操作能消掉更多的。还有一个的地方是,为了防止越界,可以将先转换成。 LeetCode[397] Integer Replacement Given a positive integer n and you can do operations as fo...

    Drinkey 评论0 收藏0
  • leetcode397. 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...

    quietin 评论0 收藏0
  • [LintCode/LeetCode] Integer Replacement

    Problem 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 re...

    fyber 评论0 收藏0
  • [LeetCode] Integer Replacement

    摘要:记一种简单的的做法先讨论边界,若为最大值,返回然后对整数分奇偶两种情况讨论,偶数除以,奇数判断是否后能被整除且不等于,若如此则,否则每次操作后计数器,循环结束后返回计数器值。 Problem Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2.I...

    XFLY 评论0 收藏0
  • LeetCode 397 整数替换[递归] HERODING的LeetCode之路

    摘要:解题思路这题就是最基础的递归运算题目,两个选择,一个是偶数,一个是奇数,偶数直接除操作,奇数变成左右两个偶数继续操作选择操作最小的,注意有一个用例是,解决方法有两种,第一就是首先把的二次幂都干掉,代码如下 ...

    HtmlCssJs 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<