[LeetCode] Integer Replacement 整數替換

來源:互聯網
上載者:User

標籤:

 

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

 

Example 1:

Input:8Output:3Explanation:8 -> 4 -> 2 -> 1

 

Example 2:

Input:7Output:4Explanation:7 -> 8 -> 4 -> 2 -> 1or7 -> 6 -> 3 -> 2 -> 1

 

這道題給了我們一個整數n,然後讓我們通過變換變為1,如果n是偶數,我們變為n/2,如果是奇數,我們可以變為n+1或n-1,讓我們求變為1的最少步驟。那麼一看道題的要求,就會感覺應該用遞迴很合適,我們直接按照規則寫出遞迴即可,注意由於有n+1的操作,所以當n為INT_MAX的時候,就有可能溢出,所以我們可以先將n轉為長整型,然後再進行運算,參見代碼如下:

 

解法一:

class Solution {public:    int integerReplacement(int n) {        if (n == 1) return 0;        if (n % 2 == 0) return 1 + integerReplacement(n / 2);        else {            long long t = n;            return 2 + min(integerReplacement((t + 1) / 2), integerReplacement((t - 1) / 2));        }    }}; 

 

我們也可以使用迭代的解法,那麼這裡就有小技巧了,當n為奇數的時候,我們什麼時候應該加1,什麼時候應該減1呢,通過觀察來說,除了3和7意外,所有加1就變成4的倍數的奇數,適合加1運算,比如15:

15 -> 16 -> 8 -> 4 -> 2 -> 1

15 -> 14 -> 7 -> 6 -> 3 -> 2 -> 1

對於7來說,加1和減1的結果相同,我們可以不用管,對於3來說,減1的步驟小,所以我們需要去掉這種情況。那麼我們如何知道某個數字加1後是否是4的倍數呢,我們可以用個小技巧,由於我們之前判定其是奇數了,那麼最右邊一位肯定是1,如果其右邊第二位也是1的話,那麼進行加1運算,進位後右邊肯定會出現兩個0,則一定是4的倍數,搞定。如果之前判定是偶數,那麼除以2即可,參見代碼如下:

 

解法二:

class Solution {public:    int integerReplacement(int n) {        long long t = n;        int cnt = 0;        while (t > 1) {            ++cnt;            if (t & 1) {                if ((t & 2) && (t != 3)) ++t;                else --t;            } else {                t >>= 1;            }        }        return cnt;    }};

 

參考資料:

https://discuss.leetcode.com/topic/58655/0ms-cpp-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)

[LeetCode] Integer Replacement 整數替換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.