forked from singlemancombat/interview-preparation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.java
More file actions
30 lines (25 loc) · 893 Bytes
/
Copy pathDivideTwoIntegers.java
File metadata and controls
30 lines (25 loc) · 893 Bytes
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
public class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 0)
return dividend >= 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
if (dividend == 0)
return 0;
if (dividend == Integer.MIN_VALUE && divisor == -1)
return Integer.MAX_VALUE;
boolean isNegative = (dividend < 0 && divisor > 0) ||
(dividend > 0 && divisor < 0);
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
int result = 0;
while (a >= b) {
int shift = 0;
while (a >= (b << shift)) {
shift++;
}
shift--;
a -= (b << shift);
result += (1 << shift);
}
return isNegative? -result: result;
}
}