您的位置:首页 > 其它

leetcode解题方案--028--Divide Two Integers

2017-11-07 21:14 423 查看

题目

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

分析

这道题还挺坑的

要考虑的点很多

比如Integer.min/-1 答案就会溢出

除数为0

被除数为0

public static int divide(int dividend, int divisor) {
if (divisor == 0) {
return Integer.MAX_VALUE;
} else if (dividend == 0) {
return 0;
} else if (divisor == -1 && dividend == Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
}
int a = dividend > 0 ? 1 : -1;
int b = divisor > 0 ? 1 : -1;
int flag = a + b;
long dividend1 = Math.abs((long) dividend);
long divisor1 = Math.abs((long) divisor);
int ans = 0;

long divisorCopy = divisor1;
while (dividend1 >= (divisor1 << 1)) {
divisor1 = divisor1 << 1;
}

while (divisor1 >= divisorCopy) {
ans = ans << 1;
if (dividend1 >= divisor1) {
dividend1 = dividend1 - divisor1;
ans++;
}
divisor1 = divisor1 >> 1;
}
if (flag == 0) {
ans = 0 - ans;
}
System.out.println(ans);
return ans;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: