-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivider.java
More file actions
46 lines (39 loc) · 1.11 KB
/
Divider.java
File metadata and controls
46 lines (39 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
42
43
44
45
46
public class Divider {
public int divide(int dividend, int divisor) {
long lDividend = (long) dividend;
long lDivisor = (long) divisor;
long sign = 1;
if (lDividend < 0) {
sign *= (-1);
lDividend = -lDividend;
}
if (lDivisor < 0) {
sign *= (-1);
lDivisor = -lDivisor;
}
if (lDivisor == 1) {
return (int) Math.min(lDividend * sign, (long) Integer.MAX_VALUE);
}
int count = 1;
while ((lDivisor << 1) < lDividend) {
count++;
lDivisor <<= 1;
}
long result = 0;
for (int i = 0; i < count; i++) {
result <<= 1;
if (lDividend >= lDivisor) {
lDividend -= lDivisor;
result |= 1;
}
lDivisor >>= 1;
}
return (int) Math.min(result * sign, (long) Integer.MAX_VALUE);
}
public void run() {
int dividend = Integer.MIN_VALUE;
int divisor = 2;
int res = divide(dividend, divisor);
System.out.println(res);
}
}