leetcode题目汇集 - Divide Two Integers
leetcode 29 - Divide Two Integers
题目要求
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路:将除数依次左移,直到无法左移
注意:
1.当被除数为Integer.MIN_VALUE,而除数为-1时,按long类型计算的话结果为2^(31),这显然 不在int范围内,因此需要单独处理。
2.abs(Integer.MIN_VALUE)不在int范围内,因此需要将其转换为long类型再进行计算
代码
public class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 0) {
return dividend >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
if (dividend == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
int result = 0;
int sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) ? -1 : 1;
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
while (a >= b) {
int shift = 0;
while (a >= (b << shift)) {
shift++;
}
a = a - (b << (shift - 1));
result += (1 << (shift - 1));
}
return sign * result;
}
}