C# --- Clean and Simple log(n) * log(n) solution


  • 0
    A

    The key is to convert numbers from positive to negative first.

    public int Divide(int dividend, int divisor) 
    {
        if(divisor == 0) return int.MaxValue;
    
        bool negative = dividend > 0 ^ divisor > 0;
        dividend = dividend <= 0 ? dividend : -dividend;
        divisor = divisor <= 0 ? divisor : -divisor;
        
        int quotation = 0;
        while( dividend <= divisor)
        {
            int power = -1;
            long curMultiples = divisor;
            while(dividend <= curMultiples + curMultiples)
            {
                power += power;
                curMultiples += curMultiples;
            }
            
            dividend -= (int)curMultiples;
            quotation += power;
        }
        
        return negative ? quotation : (quotation == int.MinValue ? int.MaxValue: 0 - quotation);
    }

Log in to reply
 

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