Created
March 16, 2020 03:46
-
-
Save vitkarpov/ff833ef753ec069a44f329f203752aed to your computer and use it in GitHub Desktop.
29. Divide Two Integers
This file contains 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) { | |
int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1; | |
long long dvd = dividend; | |
long long dvs = divisor; | |
if (dvd == INT32_MIN && dvs == -1) { | |
return INT32_MAX; | |
} | |
dvd = abs(dvd); | |
dvs = abs(dvs); | |
long long res = 0; | |
for (int i = 31; i >= 0; --i) { | |
if (dvd >= (dvs << i)) { | |
dvd -= (dvs << i); | |
res += (1 << i); | |
} | |
} | |
return sign * res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment