8ms C++ Solution


  • 0
    5
    int divide(int dividend, int divisor) {
    	if (divisor == 0) {
    		return dividend < 0 ? INT_MIN : INT_MAX;
    	}
    	if (divisor == INT_MIN) {
    		return dividend < 0 ? dividend == INT_MIN : 0;
    	}
    	unsigned int div[32], a = dividend < 0 ? -dividend : dividend, b = divisor < 0 ? -divisor : divisor, index = 0, ret = 0;
    	if (a < b) return 0;
    	div[0] = divisor;
    	while (a >= b) {
    		a -= b;
    		ret += (1 << index);
    		div[index++] = b;
    		b <<= 1;
    	}
    	while ((int)a >= div[0]) {
    		if (a >= div[--index]) {
    			a -= div[index];
    			ret += (1 << index);
    		}
    	}
    	return (dividend ^ divisor) < 0 ? -ret : (ret > INT_MAX ? INT_MAX : ret);
    }

Log in to reply
 

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