-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathDivideTwoIntegers.java
50 lines (40 loc) · 1.17 KB
/
DivideTwoIntegers.java
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
42
43
44
45
46
47
48
49
50
class Solution {
public int divide(int dividend, int divisor) {
long count =0;
boolean neg = false;
if((dividend<0 && divisor>0) || (dividend>0 && divisor<0)){
neg = true;
}
long lDividend = Math.abs((long)dividend);
long lDivisor = Math.abs((long)divisor);
if(lDivisor == 0 || (lDividend< lDivisor)){
return 0;
}
count = longDivide(lDividend, lDivisor);
if(count> Integer.MAX_VALUE){
if(neg){
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
} else {
if(neg){
return (int)(-count);
} else{
return (int)count;
}
}
}
private long longDivide(long lDividend, long ldivisor){
if(lDividend< ldivisor){
return 0;
}
long count =1; // quotient
long sum = ldivisor; // comparable dividend
while((sum+sum) <= lDividend){
sum = sum+sum;
count = count+count;
}
return count + longDivide(lDividend- sum, ldivisor);
}
}