public class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 0) {
return Integer.MAX_VALUE;
}
if (divisor == -1 && dividend == Integer.MIN_VALUE) {
return Integer.MAX_VALUE;
}
long dvd = Math.abs((long) dividend);
long dvs = Math.abs((long) divisor);
boolean negative = false;
if ((dividend >= 0) ^ (divisor >= 0)) {
negative = true;
}
int result = 0;
while (dvd >= dvs) {
int shift = 0;
while (dvd >= (dvs << shift)) {
shift++;
}
result = result + (1 << (shift - 1));
dvd = dvd - (dvs << (shift - 1));
}
if (negative) {
return -result;
} else {
return result;
}
}
}