int divide(int dividend, int divisor) {
//除数不能为零, 防止溢出(4bits: 0到7 和 -8到-1, -8除以 -1 = 8 溢出)
if(divisor == 0 || (dividend == INT_MIN && divisor == -1)) return INT_MAX;
int sign = ((divisor < 0) ^ (dividend < 0)) ? 1 : 0;
//用long类型防止溢出,注意abs和labs long long l_divisor = labs(divisor); long long l_dividend = labs(dividend); int res = 0;
while(l_dividend >= l_divisor ){ long long tmp = l_divisor; int cnt = 1;
//以十除以二为例, 当tmp = 4, cnt = 2; tmp = 8,cnt = 4; 接着推出循环(10 = 2^3 + 2^1) while(l_dividend >= (tmp << 1)){//循环三次 tmp <<= 1; cnt <<= 1; } //此时l_dividend为2; l_dividend -= tmp; res += cnt; } return sign ? -res : res; }