-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.java
More file actions
33 lines (29 loc) · 1.06 KB
/
Copy pathDivideTwoIntegers.java
File metadata and controls
33 lines (29 loc) · 1.06 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
public class Solution {
// 32 ~ 3*10 = 3*[1*(2^3) + 0*(2^2) + 1*(2^1) + 0*(2^0)]
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);
// Need to be long since b << shift may be overflow
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++;
}
a -= b << (shift - 1);
result += 1 << (shift - 1);
}
return isNegative? -result: result;
}
}