My C++ 3ms code, O(log n) time, O(1) space


  • 0
    J
    class Solution {
    public:
        int integerReplacement(int n) {
            int ones = 0, steps = 0;
            while(n!=1){
                if(!(n&1) && ones>0){ // if LSB==0 && has seen '1'
                    steps+=(ones<=1? ones*2: ones+1);
                    n+=(ones>1?1:0);
                    ones = 0;
                }else{ // if (1) LSB==1 or (2) LSB==0 && hasn't seen '1'
                    ones+=(int(n&1));
                    steps+=(1-int(n&1));
                    n>>=1;
                }
            }
            steps+=(ones<=2? ones*2: ones+2);
            return steps;
        }
    };
    

Log in to reply
 

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