资讯专栏INFORMATION COLUMN

LeetCode[397] Integer Replacement

Drinkey / 2028人阅读

摘要:复杂度思路利用位的操作。如果一个数是奇数,那么末位的位一定是。对于偶数,操作是直接除以。对于奇数的操作如果倒数第二位是,那么的操作比的操作能消掉更多的。还有一个的地方是,为了防止越界,可以将先转换成。

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
needed for n to become 1?

Example 1:

Input: 8

Output: 3

Explanation: 8 -> 4 -> 2 -> 1

Bit Manipulation

复杂度
O(1) ?, O(1)

思路
利用bit位的操作。如果这个数偶数,那么末位的bit位一定是0。如果一个数是奇数,那么末位的bit位一定是1。对于偶数,操作是直接除以2。

对于奇数的操作:
如果倒数第二位是0,那么n-1的操作比n+1的操作能消掉更多的1。
1001 + 1 = 1010
1001 - 1 = 1000
如果倒数第二位是1,那么n+1的操作能比n-1的操作消掉更多的1。
1011 + 1 = 1100
1111 + 1 = 10000

还有一个tricky的地方是,为了防止integer越界,可以将n先转换成long。long N = n;这样的处理。

代码
同样是从别的地方看到比较好的代码;

public int integerReplacement(int n) {
    // 处理大数据的时候tricky part, 用Long来代替int数据
    long N = n;
    int count = 0;
    while(N != 1) {
        if(N % 2 == 0) {
            N = N >> 1;
        }
        else {
            // corner case;
            if(N == 3) {
                count += 2;
                break;
            }
            N = (N & 2) == 2 ? N + 1 : N - 1;
        }
        count ++;
    }
    return count;
}

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

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

相关文章

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

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