log n solution


  • 0
    I

    public class Solution {
    public int Divide(int dividend, int divisor) {
    if(divisor == 0 || (divisor==-1 && dividend == Int32.MinValue)) return Int32.MaxValue;

        int sign = ((dividend >=0 && divisor >= 0) || (dividend <0 && divisor < 0)) ? 1 : -1;
        long pDividend, pDivisor;
        if(dividend < 0)
        {
            pDividend = dividend;
            pDividend = -pDividend;
            
        }
        else pDividend = dividend;
        
        if(divisor < 0)
        {
            pDivisor = divisor;
            pDivisor = -pDivisor;
        }
        else pDivisor = divisor;
        
        int result = 0;
        int factor = 1;
        
        if(divisor == 1) return dividend;
        if(divisor == -1) return -dividend;
        
        while(pDividend >= pDivisor)
        {
            long x = pDividend - pDivisor * factor;
            if(x >= 0){
            pDividend = x;                     
            result +=  factor;
            factor <<= 1;   
            }
            else
            {
                factor = 1;
            }
            
        }
        if (sign == -1) return -result;
        else return result;
    }
    

    }


Log in to reply
 

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