forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdivide.cpp
More file actions
47 lines (40 loc) · 986 Bytes
/
divide.cpp
File metadata and controls
47 lines (40 loc) · 986 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <cmath>
using namespace std;
typedef long long LL;
class Solution {
public:
int divide(int dividend, int divisor) {
bool pos = true;
if (dividend < 0) pos = !pos;
if (divisor < 0) pos = !pos;
LL d1 = abs((LL)dividend);
LL d2 = abs((LL)divisor);
LL a = d1, b = d2, c = 1;
while (a > b) {
b <<= 1;
c <<= 1;
}
int res = 0;
while (a >= d2) {
while (a >= b) {
a -= b;
res += c;
}
b >>= 1;
c >>= 1;
}
if (!pos) res = -res;
return res;
}
};
int main() {
Solution s = Solution();
cout << s.divide(13, 5) << endl;
cout << s.divide(15, 5) << endl;
cout << s.divide(3, 5) << endl;
cout << s.divide(13, -5) << endl;
cout << s.divide(-13, 5) << endl;
cout << s.divide(-1010369383, -2147483648) << endl;
return 0;
}