LeetCode 397. Integer Replacement 时间复杂度(O(logn))

时间复杂度(O(logn))

class Solution {
public:
    int integerReplacement(int n) {
        if(2147483647==n) return 32;
        int count=0;
        while(n>1){
            if(n%2==0)
                n = n/2;
            else{
                int count1 = get1Count(n-1);
                int count2 = get1Count(n+1);
                if(count1<count2)
                    n = n-1;
                else if(count1==count2)
                    if(n>3)     n = n+1;
                    else        n = n-1;
                else    n = n+1;
            }
            ++count;
        }
        return count;
    }
    int get1Count(int n){
        if(n<=1)return n;
        int count=0;
        while(n>0){
            if(n&0x1)  ++count;
            n = n>>1;
        }
        return count;
    }
};

猜你喜欢

转载自blog.csdn.net/ziyue246/article/details/81430029
今日推荐