您的位置:首页 > 编程语言 > Java开发

LeetCode : Divide Two Integers [java]

2016-03-09 15:10 417 查看
Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

思路:注意使用long进行计算,防止int溢出,然后再判断溢出时重置。

public class Solution {
public int divide(int dividend, int divisor) {
if(divisor == 0){
return 0;
}
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
long res = 0;
boolean isPositive = ((dividend ^ divisor) >> 31) == 0;
while (a >= b) {
long c = b;
for (long i = 0; a >= c; i++, c <<= 1) {
a -= c;
res += 1 << i;
if ((isPositive && res > Integer.MAX_VALUE) || (!isPositive && -res < Integer.MIN_VALUE)) {
return Integer.MAX_VALUE;
}
}
}
return isPositive ? (int) res : (int) -res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: