29 Divide Two Integers

来源:互联网 发布:安卓串口软件 编辑:程序博客网 时间:2024/05/21 19:49
/*
 * 思路:每次减轻一个除数会超时,所以要一次减去多个除数来加速
 * 注意:题中说“If it is overflow, return MAX_INT.”注意当数大于MAX_INT时进行处理
 * int 的范围为-2147483648~2147483647,而且Math.abs(-2147483648)的值还是-2147483648
 * 而Math.abs((long)-2147483648)输出的是2147483648

 */

public class Solution {
public int divide(int dividend, int divisor) {
int flag = 1;
if(dividend<0){
flag = -flag;
}
if(dividend>Integer.MAX_VALUE){
dividend = Integer.MAX_VALUE;
}
if(divisor<0){
flag = -flag;
}
if(divisor>Integer.MAX_VALUE){
divisor = Integer.MAX_VALUE;
}
long t1 = Math.abs((long)dividend);
long t2 = Math.abs((long)divisor);
long res = 0;
while(t1>=t2){
long t3 = t2;
for(int i=0;t1>=t3;++i,t3<<=1){
t1-=t3;
res+=(1<<i);
}
}
if(flag<0){
res = -res;
}
if(res>Integer.MAX_VALUE){
res = Integer.MAX_VALUE;
}
return (int)res;
    }
}

0 0