-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.js
55 lines (48 loc) · 1.15 KB
/
res.js
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
/**
* res.js
* @authors Joe Jiang ([email protected])
* @date 2017-03-01 21:57:06
* @version $Id$
*/
/**
* Divide two integers without using multiplication, division and mod operator.
*
* If it is overflow, return MAX_INT.
*
* Pay attention to Javascript Bitwise operators
* http://www.ecma-international.org/ecma-262/5.1/#sec-11.10
*
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
let divide = function(dividend, divisor) {
let MIN_INT = -2147483648,
MAX_INT = 2147483647,
positive = 0;
if(!divisor || (dividend === MIN_INT && divisor === -1)) {
return MAX_INT;
}
let res = 0;
if (dividend < 0) {
dividend = -dividend;
positive += 1;
}
if (divisor < 0) {
divisor = -divisor;
positive += 1;
}
while (dividend >= divisor) {
let tmpres = 1, tmpdiv = divisor;
while ((dividend >> 1) >= tmpdiv) {
tmpres <<= 1;
tmpdiv <<= 1;
}
res += tmpres;
dividend -= tmpdiv;
}
if (positive === 1) {
return -res;
}
return res;
};