Last active
June 10, 2018 03:46
-
-
Save Siyu-Lei/556f42069b91a85a3eaea5f4397f56bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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