forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivideTwoIntegers.cpp
More file actions
43 lines (40 loc) · 1.02 KB
/
DivideTwoIntegers.cpp
File metadata and controls
43 lines (40 loc) · 1.02 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
class Solution {
public:
int divide(int dividend, int divisor) {
if(divisor==1) {
return dividend;
}
long long int dividend_ = dividend;
long long int divisor_ = divisor;
bool isNeg = false;
if( (dividend^divisor) < 0) {
isNeg = true;
}
if(dividend<0) {
dividend_ = -dividend_;
}
if(divisor<0) {
divisor_ = -divisor_;
}
long long int numdigit = 0;
while((divisor_ << numdigit) <= dividend_) {
numdigit++;
}
numdigit--;
long long int res = 0;
while(numdigit>=0) {
if(dividend_ >= (divisor_ << numdigit)) {
dividend_ -= (divisor_ << numdigit);
res += (1LL << numdigit);
}
numdigit--;
}
if(isNeg) {
return (int)(-res);
}
if(res > 0x7fffffffLL) {
return 0x7fffffff;
}
return res;
}
};