成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Leetcode 397. Integer Replacement

sutaking / 2698人閱讀

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;

}

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/66429.html

相關(guān)文章

  • LeetCode[397] Integer Replacement

    摘要:復(fù)雜度思路利用位的操作。如果一個(gè)數(shù)是奇數(shù),那么末位的位一定是。對(duì)于偶數(shù),操作是直接除以。對(duì)于奇數(shù)的操作如果倒數(shù)第二位是,那么的操作比的操作能消掉更多的。還有一個(gè)的地方是,為了防止越界,可以將先轉(zhuǎn)換成。 LeetCode[397] Integer Replacement Given a positive integer n and you can do operations as fo...

    Drinkey 評(píng)論0 收藏0
  • leetcode397. Integer Replacement

    摘要:題目要求思路和代碼可以發(fā)現(xiàn)除二后所得到的結(jié)果一定優(yōu)于加減。因此,如果當(dāng)前奇數(shù)除二為偶數(shù),則直接做除法,否則將當(dāng)前奇數(shù)加一再除以二,得到偶數(shù)的結(jié)果。 題目要求 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 評(píng)論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 評(píng)論0 收藏0
  • [LeetCode] Integer Replacement

    摘要:記一種簡單的的做法先討論邊界,若為最大值,返回然后對(duì)整數(shù)分奇偶兩種情況討論,偶數(shù)除以,奇數(shù)判斷是否后能被整除且不等于,若如此則,否則每次操作后計(jì)數(shù)器,循環(huán)結(jié)束后返回計(jì)數(shù)器值。 Problem Given a positive integer n and you can do operations as follow: If n is even, replace n with n/2.I...

    XFLY 評(píng)論0 收藏0
  • LeetCode 397 整數(shù)替換[遞歸] HERODING的LeetCode之路

    摘要:解題思路這題就是最基礎(chǔ)的遞歸運(yùn)算題目,兩個(gè)選擇,一個(gè)是偶數(shù),一個(gè)是奇數(shù),偶數(shù)直接除操作,奇數(shù)變成左右兩個(gè)偶數(shù)繼續(xù)操作選擇操作最小的,注意有一個(gè)用例是,解決方法有兩種,第一就是首先把的二次冪都干掉,代碼如下 ...

    HtmlCssJs 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<