Share my 0ms C++ code...


  • 2

    We can use bit-operation to accelerate and use long long to avoid overflow.

    class Solution {
    public:
        int integerReplacement(int n) {
            return countRec(n,0);
        }
    private:
        int countRec(int n,int count){
            if(n==1)
                return count;
            if(n==3)
                return count+2;
            if((n&1)==0){
                return countRec((n>>1),count+1);
            }
            long long a=(long long)n+1;
            if((a&3)==0){
                a=a>>1;
                return countRec((int)a,count+2);
            }
            return countRec(n-1,count+1);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.