15 line solution using negative bit-shift, avoid overflow


  • 1
    E
       int divide(int dividend, int divisor) {
        bool flag = false; 
        if ((dividend > 0 ^ divisor > 0 )){
            flag = true; 
        }
        if(dividend == INT_MIN && divisor == -1) return INT_MAX;
        dividend = dividend<0?dividend:-dividend;
        divisor = divisor<0?divisor:-divisor;
        long d  = divisor;
        int cnt = 0;
        while(d>=dividend ){
            d = d<<1;cnt++;
        }
        if(cnt == 0) return 0;
        d = d >> 1;  
       return flag?-1*(pow(2,cnt-1)+divide(dividend-d,divisor)):pow(2,cnt-1)+divide(dividend-d,divisor);
        
    }

Log in to reply
 

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