-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.java
More file actions
54 lines (34 loc) · 1.27 KB
/
Copy pathDivideTwoIntegers.java
File metadata and controls
54 lines (34 loc) · 1.27 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
47
48
49
50
51
52
53
54
package LeetcodePractice;
public class DivideTwoIntegers {
public static int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
if (dividend == Integer.MIN_VALUE && divisor == 1) {
return Integer.MIN_VALUE;
}
int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1;
long lDividend = Math.abs((long) dividend);
long lDivisor = Math.abs((long) divisor);
long result = 0;
while (lDividend >= lDivisor) {
long temp = lDivisor;
long multiple = 1;
while (lDividend >= (temp << 1)) {
temp <<= 1;
multiple <<= 1;
}
lDividend -= temp;
result += multiple;
}
result = sign * result;
if (result > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (result < Integer.MIN_VALUE) return Integer.MIN_VALUE;
return (int) result;
}
public static void main(String[] args) {
System.out.println(divide(10, 3));
System.out.println(divide(7, -3));
System.out.println(divide(-2147483648, -1));
}
}