forked from Andyy-18/CPP-BASICS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Divide Two Integers
44 lines (38 loc) · 1.29 KB
/
Divide Two Integers
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
public int divide(int dividen, int divisor) {
if (divisor == Integer.MIN_VALUE) {
return dividen == Integer.MIN_VALUE ? 1 : 0;
}
if (dividen == Integer.MIN_VALUE) {
if (divisor == 1) {
return dividen;
} else if (divisor == -1) {
return Integer.MAX_VALUE;
}
} else if (dividen == Integer.MAX_VALUE) {
if (divisor == 1) {
return dividen;
} else if (divisor == -1) {
return -dividen;
}
}
long dividenLong = dividen;
long divisorLong = divisor;
boolean sign = false;
if (dividenLong < 0 && divisorLong < 0) {
dividenLong = -dividenLong;
divisorLong = -divisorLong;
} else if (dividenLong < 0 && divisorLong > 0) {
sign = true;
dividenLong = -dividenLong;
} else if (dividenLong > 0 && divisorLong < 0) {
sign = true;
divisorLong = -divisorLong;
}
long ans = 0;
while (dividenLong >= divisorLong) {
dividenLong -= divisorLong;
ans++;
}
ans = sign ? -ans : ans;
return ans > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) ans;
}