Commit 62325c54 authored by Sadman Kazi's avatar Sadman Kazi 🎸

Solve divide two integers

parent 0c108e57
#include <iostream>
#include <limits>
class Solution {
public:
int divide(int dividend, int divisor) {
int q = 0;
if (dividend == 0) return 0;
if (divisor == 0) return std::numeric_limits<int>::max();
if (divisor == -1 && dividend == std::numeric_limits<int>::min())
return std::numeric_limits<int>::max();
bool sign = false; // false is positive
if (dividend > 0) {
sign = !sign;
dividend = -dividend;
}
if (divisor > 0) {
sign = !sign;
divisor = -divisor;
}
int cur_div = divisor;
while (divisor >= dividend) {
int cur_q = 1;
while (cur_div > dividend) {
cur_div = cur_div << 1;
if (cur_div < dividend) break;
else if (cur_div == dividend) {
cur_q += cur_q;
break;
}
else cur_q = cur_q+cur_q;
}
if (cur_div != dividend) cur_div = cur_div >> 1;
dividend -= cur_div;
cur_div = divisor;
q += cur_q;
}
if (sign) return -q;
else return q;
}
};
int main () {
int n;
std::cin >> n;
int a, b;
Solution sol;
for (int i = 0; i < n; i++) {
std::cin >> a >> b;
std::cout << sol.divide(a, b) << std::endl;
}
}
8
-2147483648 -1
0 1
-5 -2
2 3
1 1
5 2
-2147483648 -3
-2147483648 1
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment