Share my elegant 3ms C++ solution


  • 0
    C
    class Solution {
    public:
        unsigned int getFirstSetBitPos(long n)
        {
            return log2(n & -n) + 1;
        }
        
        int integerReplacement(int n) {
            int c = 0;
            long ln = n;
            
            while(ln != 1)
            {
                if((ln & 1) == 0)
                    ln = ln / 2;
                else 
                {
                    if(ln == 3 || getFirstSetBitPos(ln-1) > getFirstSetBitPos(ln+1) )
                        --ln;
                    else
                        ++ln;
                }
                
                c++;
            }
            
            return c;
        }
    };

Log in to reply
 

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