Skip to content

Commit a44cf5a

Browse files
committed
leetcode 2/6/2014
1 parent b1ff66c commit a44cf5a

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

‎LeetCode/divide.cpp‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include <iostream>
2+
#include <cmath>
3+
using namespace std;
4+
5+
typedef long long LL;
6+
7+
class Solution {
8+
public:
9+
int divide(int dividend, int divisor) {
10+
bool pos = true;
11+
if (dividend < 0) pos = !pos;
12+
if (divisor < 0) pos = !pos;
13+
14+
LL d1 = abs((LL)dividend);
15+
LL d2 = abs((LL)divisor);
16+
17+
LL a = d1, b = d2, c = 1;
18+
while (a > b) {
19+
b <<= 1;
20+
c <<= 1;
21+
}
22+
23+
int res = 0;
24+
while (a >= d2) {
25+
while (a >= b) {
26+
a -= b;
27+
res += c;
28+
}
29+
b >>= 1;
30+
c >>= 1;
31+
}
32+
33+
if (!pos) res = -res;
34+
return res;
35+
}
36+
};
37+
38+
int main() {
39+
Solution s = Solution();
40+
cout << s.divide(13, 5) << endl;
41+
cout << s.divide(15, 5) << endl;
42+
cout << s.divide(3, 5) << endl;
43+
cout << s.divide(13, -5) << endl;
44+
cout << s.divide(-13, 5) << endl;
45+
cout << s.divide(-1010369383, -2147483648) << endl;
46+
return 0;
47+
}

0 commit comments

Comments
 (0)