From 9dfe1b34be3d65c64b25a041101898f8a2ec8f1b Mon Sep 17 00:00:00 2001 From: Emmanuel Hernandez Date: Tue, 19 Dec 2023 13:33:17 -0600 Subject: [PATCH] solve divide two integers problem using bit manipulation --- .../DivideTwoIntegers/main.cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Bit-manipulationTechniques/DivideTwoIntegers/main.cpp diff --git a/Bit-manipulationTechniques/DivideTwoIntegers/main.cpp b/Bit-manipulationTechniques/DivideTwoIntegers/main.cpp new file mode 100644 index 0000000..8d164cf --- /dev/null +++ b/Bit-manipulationTechniques/DivideTwoIntegers/main.cpp @@ -0,0 +1,63 @@ +#include +#include + +using namespace std; + +int divide(int dividend, int divisor) +{ + if (dividend == divisor) + { + return 1; + } + + bool isPositive = dividend > 0 == divisor > 0; // true both dividend and divisor have the same sign + unsigned int divd = abs(dividend); // short for dividend since this name is already used + unsigned int divs = abs(divisor); // short for divisor since this name is already used + unsigned int ans = 0; + + // dividend = quotient * divisor + remain + while (divd >= divs) + { + int exp = 0; + + /* + * "<<" left-shift bitwise operator. a << b moves the bits in "a" by "b" + * positions. Given as a result: a * 2^b + * + * This loop will increment the exp until the result of: + * divisor * 2^exp + * is greater than the dividend. + */ + while ((divs << (exp + 1)) < divd) + { + exp++; + } + + /* + * This will end up in adding all the powers of 2 that compose the quotient + * i.e. getting the value of quotient by a binary representation. + */ + ans += (1 << exp); // ans += 2^exp + divd = divd - (divs << exp); + } + + if (ans == (1 << 31) && isPositive) + { + return INT_MAX; + } + + return isPositive ? ans : -ans; +} + +int main() +{ + int dividend; + cin >> dividend; + + int divisor; + cin >> divisor; + + cout << "Result: " << divide(dividend, divisor) << endl; + + return 0; +}