Divide Two Integers
If it is overflow, return MAX_INT.
思路:这个题算法上不是很难,但是通过率相当低,只有15%,果然,自己在写完之后,各种出错,而且错误不是算法上的错误,是各种边界值没有考虑到,很多溢出错误等。下面是具体代码,有详细注释。
public class Solution {
public int divide(int dividend, int divisor) {
long a = dividend;
long b = divisor;
if(b == 0 || (a == Integer.MIN_VALUE && b == -1)){//如果被除数为0或溢出
return Integer.MAX_VALUE;
}
boolean isNegative = false;//是否负数
//将负数转成正数
if(a < 0 && b > 0){
isNegative = true;
a = -a;
}else if(a > 0 && b < 0){
isNegative = true;
b = -b;
}else if(a < 0 && b < 0){
a = -a;
b = -b;
}
if(b == 1){
return (int) (isNegative?-a:a);
}
//如果被除数大,返回0
if(a < b){
return 0;
}
divisor = (int) b;//如果是负,将转变为正数
int step = 1;
while(b < a){//如果b<a,则b = b*2
step <<= 1;//右移一位,相当于乘于2
b <<= 1;//b = b*2
}
if(b == a){//如果相等,直接返回
return isNegative? -step : step;//判断是否为负数
}
dividend = (int) (a - (b >> 1));
step >>= 1;
int num = step + divide(dividend,divisor);//递归调用
return isNegative?-num:num;//返回结果,并判断正负
}
}