国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Leetcode 397. Integer Replacement

sutaking / 2690人閱讀

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;

}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/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元查看
<