Created
March 10, 2020 19:16
-
-
Save itsjohncs/09ea2acb2c36f12f6622b771a3d03824 to your computer and use it in GitHub Desktop.
Solution to the "Divide Two Integers" problem on leetcode
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
| #include <stdio.h> | |
| #include <stdbool.h> | |
| #include <limits.h> | |
| // Leftshift by 3 is equivalent to multiplying by 8 | |
| #define BITS_IN(a) (sizeof(a) << 3) | |
| bool maybeLeftShift(unsigned int const a, int const b, unsigned int * const out) { | |
| if (b == 0 || (a >> (BITS_IN(a) - b)) == 0) { | |
| *out = a << b; | |
| return true; | |
| } | |
| return false; | |
| } | |
| int divide(int dividend, int divisor) { | |
| bool const isResultNegative = (dividend < 0 && divisor > 0) || | |
| (dividend > 0 && divisor < 0); | |
| unsigned int const udividend = | |
| dividend < 0 ? | |
| -((unsigned int)dividend) : | |
| dividend; | |
| unsigned int const udivisor = | |
| divisor < 0 ? | |
| -((unsigned int)divisor) : | |
| divisor; | |
| unsigned int remaining = udividend; | |
| unsigned int quotient = 0; | |
| for (int i = BITS_IN(unsigned int) - 1; i >= 0; --i) { | |
| unsigned int divisorTimes2ToTheI; | |
| if (!maybeLeftShift(udivisor, i, &divisorTimes2ToTheI)) { | |
| continue; | |
| } | |
| if (remaining >= divisorTimes2ToTheI) { | |
| remaining -= divisorTimes2ToTheI; | |
| quotient += 1u << i; | |
| } | |
| } | |
| if (isResultNegative) { | |
| if (quotient > -((unsigned int)INT_MIN)) { | |
| return INT_MAX; | |
| } | |
| return -quotient; | |
| } else { | |
| if (quotient > INT_MAX) { | |
| return INT_MAX; | |
| } | |
| return quotient; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment