// 5.2
// Divide Two Integers
// Divide two integers without using multiplication, division and mod operator.
// If it is overflow, return MAX_INT.
public static int divide(int dividend, int divisor) {
int tempDividend = Math.abs(dividend);
int tempDivisor = Math.abs(divisor);
if (tempDividend == Integer.MIN_VALUE) {
tempDividend = Integer.MAX_VALUE;
}
if (tempDivisor == Integer.MIN_VALUE) {
tempDivisor = Integer.MAX_VALUE;
}
if (divisor == 0) {
return Integer.MAX_VALUE;
} else if (tempDividend < tempDivisor || tempDivisor == 0) {
return 0;
}
int flag = dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0 ? -1 : 1;
if (flag == 1) {
return divideRes(tempDividend, tempDivisor);
} else {
return -divideRes(tempDividend, tempDivisor);
}
}
static public int divideRes(int dividend, int divisor) {
if (dividend < divisor) {
return 0;
}
int sum = divisor;
int mul = 1;
while ((sum + sum) < dividend) {
sum += sum;
mul += mul;
}
return mul + divideRes(dividend - sum, divisor);
}
网友评论