资讯专栏INFORMATION COLUMN

leetcode397. Integer Replacement

quietin / 2114人阅读

摘要:题目要求思路和代码可以发现除二后所得到的结果一定优于加减。因此,如果当前奇数除二为偶数,则直接做除法,否则将当前奇数加一再除以二,得到偶数的结果。

题目要求
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 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
思路和代码

可以发现除二后所得到的结果一定优于加减1。因此,如果当前奇数除二为偶数,则直接做除法,否则将当前奇数加一再除以二,得到偶数的结果。

    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/72427.html

相关文章

  • LeetCode[397] Integer Replacement

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

    Drinkey 评论0 收藏0
  • Leetcode 397. 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 can replace n with either n + 1 or n - 1. What is the minimum number of replacements ...

    sutaking 评论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条评论

quietin

|高级讲师

TA的文章

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