-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path29.zy445566.js
44 lines (42 loc) · 1.06 KB
/
29.zy445566.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
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
var divide = function(dividend, divisor) {
let fh = true;
if (dividend<0) {
dividend = - dividend;
fh = false;
}
if (divisor<0) {
divisor = - divisor;
fh = !fh;
}
let res = 0;
while (dividend>=divisor) {
let doubleisor = divisor;
let doubleRes = 1;
while (dividend>=doubleisor) {
// can't use << ,because max is Math.pow(2,31) and sign
let tmpDoubleisor = doubleisor+doubleisor;
let tmpDoubleRes = doubleRes+doubleRes;
if (dividend>=tmpDoubleisor) {
doubleisor = tmpDoubleisor;
doubleRes = tmpDoubleRes;
} else {
dividend-=doubleisor;
res+=doubleRes;
}
}
}
let max = Math.pow(2,31)-1;
let min = Math.pow(2,31);
if (fh && res > max) {
return max;
}
if (!fh && res > min) {
return -min;
}
return fh?res:-res;
};