forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdivide-two-integers(AC).cpp
More file actions
54 lines (49 loc) · 1 KB
/
divide-two-integers(AC).cpp
File metadata and controls
54 lines (49 loc) · 1 KB
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
48
49
50
51
52
53
54
#include <climits>
using namespace std;
typedef long long int LL;
class Solution {
public:
/**
* @param dividend the dividend
* @param divisor the divisor
* @return the result
*/
int divide(int dividend, int divisor) {
LL f = 1;
LL a = dividend;
LL b = divisor;
LL base;
if (a == 0) {
return 0;
}
if (a < 0) {
a = -a;
f = -f;
}
if (b < 0) {
b = -b;
f = -f;
}
LL b2;
base = b;
b2 = 1;
while ((base << 1) <= a) {
base <<= 1;
b2 <<= 1;
}
LL ans = 0;
while (base >= b) {
if (a >= base) {
a -= base;
ans += b2;
}
base >>= 1;
b2 >>= 1;
}
ans *= f;
if (ans < INT_MIN || ans > INT_MAX) {
ans = INT_MAX;
}
return ans;
}
};