LeetCode - Divide Two Integers
Problem description
Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend by divisor.
The integer division should truncate toward zero, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
Example 1:
1
2
3
Input: dividend = 10, divisor = 3
Output: 3
Explanation: 10/3 = truncate(3.33333..) = 3.
Example 2:
1
2
3
Input: dividend = 7, divisor = -3
Output: -2
Explanation: 7/-3 = truncate(-2.33333..) = -2.
Note:
-
Both dividend and divisor will be 32-bit signed integers.
-
The divisor will never be 0.
-
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
Analysis
Basic idea is to use minus to mock divide, and should double the divisor to improve efficiency.
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class DivideTwoIntegers {
public int divide(int dividend, int divisor) {
int overflow = Integer.MAX_VALUE;
if (dividend == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == -1){ // overflow
return overflow;
}
int factor = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ? -1 : 1;
dividend = -Math.abs(dividend);
divisor = -Math.abs(divisor);
int res = 0;
while (dividend <= divisor){
int count = 1;
int sum = divisor;
while (dividend <= sum + sum){
if (sum + sum > sum){ // sum +sum may overflow
break;
}
sum += sum;
count += count;
}
res += count;
dividend -= sum;
}
return res * factor;
}
}
There are some tricky skills here, first if input will result a overflow, early return it. Second, to make dividend and divisor both negative to avoid the Integer.MAX_VALUE to become 0 when do Math.abs. And if (sum + sum) > sum, since sum is negative, we can make sure that sum + sum will get a overflow and should break it.
What to improve
- sum + sum overflow is forgotten, should be more careful about + operation.