1. 程式人生 > >[leetcode]397. Integer Replacement

[leetcode]397. Integer Replacement

nbsp 行處理 tco amp 比較 特殊 ger 就是 快的

public int integerReplacement(int n) {
        /*
        可以將問題想做是一串二進制,怎麽把二進制最快的處理到只剩下一位1
        問題的關鍵是奇數的情況有兩種,不確定用哪一種,如果兩種都嘗試會TLE
        +1或者-1,更快的是能盡快消除一位或者幾位
        看了答案,方法是盡快能讓後兩位都變成0,也就是可以連續除以2:
        奇數的最後一位肯定是1,如果倒數第二位是1,那麽+1比較好
        如果倒數第二位是0,那麽-1比較好
         */
        int res = 0;
        
long num = n; while (num!=1) { if (num%2==0) num/=2; else { //3是一種特殊情況,它需要-1 if (num==3) { res+=2; break; } //判斷倒數第二位進行處理
num = (num&2)==2?num+1:num-1; } res++; } return res; }

[leetcode]397. Integer Replacement