-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode29.cpp
46 lines (43 loc) · 1.02 KB
/
leetcode29.cpp
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 == -2147483648 && divisor == -1)
{
//change these two number to positive will overflow
return 2147483647;
}
static long long int array[40];
// change number to positive
long long a = llabs((long long)dividend);
long long b = llabs((long long)divisor);
int ret = 0;
long long sum = 0;
int i = -1;
//equal to b*2^i
while(b <= a)
{
array[++i] = b;
b <<= 1;
}
for(int j = i; j >= 0; j--)
{
if(sum+array[j] > a)
{
continue;
}
else
{
sum += array[j];
ret += pow(2, j);
}
}
if((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
{
return -ret;
}
else
{
return ret;
}
}
};