-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathDivide Two Integers
57 lines (43 loc) · 1.07 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
/**
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
*/
// TIME LIMIT EXCEEDED
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
var divide = function(dividend, divisor) {
if (divisor === 0) {
return Number.MAX_VALUE;
}
if (dividend === 0) {
return 0;
}
var result = 0,
isNeg = false,
temp,
i = 0;
if (dividend > 0 && divisor < 0 || dividend < 0 && divisor > 0) {
isNeg = true;
}
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
if (divisor === 1 || divisor === -1) {
return isNeg? -dividend : dividend;
}
temp = divisor;
while (divisor << (i + 1) <= dividend) {
i++;
}
while (dividend >= divisor) {
temp = divisor << i;
if (dividend >= temp) {
result += (1 << i);
dividend -= temp;
}
i--;
}
return isNeg? -result : result;
};