-
Notifications
You must be signed in to change notification settings - Fork 1
/
DivideTwoIntegers.cpp
46 lines (41 loc) · 1.04 KB
/
DivideTwoIntegers.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
/*
Divide two integers without using multiplication, division and mod operator.
*/
class Solution {
public:
int divide(int dividend, int divisor) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(dividend==0)
return 0;
// assert(divisor!=0);
int sign = 1;
if(dividend<0)
sign = -1;
if(divisor<0)
sign = sign*(-1);
long long ld = abs((long long) dividend); //abs
long long ls = abs((long long) divisor);
long long count = 1;
long long num = ls;
long long result = 0;
if(ls>ld)
return 0;
while(num < ld)
{
count<<=1;
num<<=1;
}
while(num>=ls)
{
if(num<=ld)
{
ld -= num;
result += count;
}
num>>=1;
count>>=1;
}
return sign*result;
}
};