forked from naniannuowei/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29. Divide Two Integers
46 lines (42 loc) · 959 Bytes
/
29. Divide Two Integers
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
class Solution {
public:
int divide(int dividend, int divisor) {
if(dividend ==0)
{
return 0;
}
if(divisor == 1)
{
return dividend;
}
if(divisor == -1)
{
if(dividend == INT_MIN)
{
return INT_MAX;
}
return -dividend;
}
int flag = 1;
if((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))
{
flag = -1;
}
if(dividend > 0) dividend = -dividend;
if(divisor > 0) divisor = -divisor;
int res = div(dividend, divisor);
return flag>0 ? res : -res;
}
int div(int a, int b)
{
if(a > b) return 0;
int count = 1;
int tb = b;
while((a-tb) <= tb)
{
count = count + count;
tb = tb + tb;
}
return count + div(a-tb, b);
}
};