forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivide Two Integers.java
More file actions
41 lines (31 loc) · 1.11 KB
/
Divide Two Integers.java
File metadata and controls
41 lines (31 loc) · 1.11 KB
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
36
37
38
39
40
41
class Solution {
public int divide(int dividend, int divisor) {
boolean isNeg = false;
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
isNeg = true;
}
int ans = 0;
long Ldividend = Math.abs((long) dividend);
long Ldivisor = Math.abs((long) divisor);
if (Ldivisor == 0) return Integer.MAX_VALUE;
if (Ldividend == 0 || (Ldividend < Ldivisor)) return 0;
long quot = ldivide(Ldividend, Ldivisor);
if(quot > Integer.MAX_VALUE) {
ans = isNeg == false ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
else {
ans = (int)(isNeg ? -quot : quot);
}
return ans;
}
private long ldivide(long ldividend, long ldivisor) {
if (ldividend < ldivisor) return 0;
long sum = ldivisor;
long multiple = 1;
while ((sum+sum) <= ldividend) {
sum += sum;
multiple += multiple;
}
return multiple + ldivide(ldividend - sum, ldivisor);
}
}