Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Created March 16, 2020 03:46
Show Gist options
  • Save vitkarpov/ff833ef753ec069a44f329f203752aed to your computer and use it in GitHub Desktop.
Save vitkarpov/ff833ef753ec069a44f329f203752aed to your computer and use it in GitHub Desktop.
29. Divide Two Integers
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