Skip to content

Instantly share code, notes, and snippets.

@Siyu-Lei
Last active June 10, 2018 03:46
Show Gist options
  • Save Siyu-Lei/556f42069b91a85a3eaea5f4397f56bb to your computer and use it in GitHub Desktop.
Save Siyu-Lei/556f42069b91a85a3eaea5f4397f56bb to your computer and use it in GitHub Desktop.
class Solution {
public int divide(int dividend, int divisor) {
// according to note:
// For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
boolean sign = (dividend > 0) ^ (divisor > 0);
long dvd = Math.abs((long) dividend);
long dvs = Math.abs((long) divisor);
int res = 0;
while (dvd >= dvs) {
long temp = dvs;
int multiple = 1;
while (dvd >= (temp << 1)) {
multiple <<= 1;
temp <<= 1;
}
dvd -= temp;
res += multiple;
}
return sign ? -res : res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment