0ms cpp solution


  • 0
    T
    int integerReplacement(int n) {
            int counter = 0;
            if(n == INT_MAX) return 32;
            while(n > 1){
                counter++;
                if(n & 1)
                    if((n & 2) && n != 3) n++;
                    else n--;
                else
                    n >>= 1;
            }
            return counter;
        }

  • 0
    T

    recursive version:

    int integerReplacement(int n) {
            if(n <= 1) return 0;
            if(n <= 3) return 1 + integerReplacement(n-1);
            if(n == INT_MAX) return 32;
            if(n&1) return 1 + ((n&2) ? integerReplacement(n+1) : integerReplacement(n-1));
            return 1 + integerReplacement(n>>1);
        }

Log in to reply
 

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