forked from selfboot/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path29_DivideTwoIntegers.cpp
More file actions
44 lines (39 loc) · 827 Bytes
/
29_DivideTwoIntegers.cpp
File metadata and controls
44 lines (39 loc) · 827 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
/*
* @Author: xuezaigds@gmail.com
* @Last Modified time: 2016-04-06 22:39:41
*/
class Solution {
public:
// Refer to:
// https://leetcode.com/discuss/38997/detailed-explained-8ms-c-solution
int divide(int dividend, int divisor) {
if(!divisor || (dividend==INT_MIN && divisor==-1))
return INT_MAX;
bool positive = ((dividend < 0) == (divisor < 0));
long long dvd = labs(dividend);
long long dvs = labs(divisor);
int ans = 0;
while(dvd >= dvs){
long long temp=dvs, multiple=1;
while(dvd >= (temp<<1)){
temp <<= 1;
multiple <<= 1;
}
ans += multiple;
dvd -= temp;
}
return positive ? ans:-ans;
}
};
/*
0
1
12
3
125
-4
1
-1
2147483647
1
*/