a c++ solution


  • 0
    W
    class Solution 
    {
    public:    
        int64_t divide(int64_t dividend, int64_t divisor) 
        {   
            int64_t d=dividend;
            int64_t dd=divisor;
            
            if (!divisor || (dividend == INT_MIN && divisor == -1))
                return INT_MAX;
            if(dividend == divisor)
                return 1;
            if(dividend == 1 && divisor == -1)
                return -1;
            if(divisor == 1)
                return dividend;
            
            dividend=abs(dividend);
            divisor=abs(divisor);       
            
            int64_t count=0;
            if(divisor == 2)
                count = dividend >> 1;
            else
            {
                while(dividend > divisor)
                {
                    int countx=1;
                    int64_t divisorx=divisor;
                    while(dividend > divisorx<<1)
                    {
                        divisorx <<= 1;
                        countx <<=1;
                    }
                    count += countx;
                    dividend -= divisorx;
                }
            }        
            return d < 0 && dd > 0 || d > 0 && dd < 0 ? -count : count;        
        }
    };
    

Log in to reply
 

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