-
Notifications
You must be signed in to change notification settings - Fork 20
/
DivideTwoIntegers.js
79 lines (67 loc) · 1.53 KB
/
DivideTwoIntegers.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Divide two integers without using multiplication, division and mod operator.
*
* If it is overflow, return MAX_INT.
*
* Accepted.
*/
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
let divide = function (dividend, divisor) {
let sym = dividend * divisor < 0 ? -1 : 1;
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
let tmp, result = 0;
while (dividend >= divisor) {
tmp = 1;
while (divisor * tmp <= dividend) {
tmp *= 2;
}
dividend = dividend - divisor * parseInt(tmp / 2);
result += parseInt(tmp / 2);
}
if (-1 === sym) {
return sym * (result <= 2147483648 ? result : 2147483648);
}
return result <= 2147483647 ? result : 2147483647;
};
const INT_MIN_VALUE = -2147483648;
const INT_MAX_VALUE = 2147483647;
if (divide(1, 1) === 1) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(0, 1) === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(-1, -1) === 1) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(INT_MAX_VALUE, 1) === 2147483647) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(INT_MAX_VALUE, INT_MIN_VALUE) === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(INT_MIN_VALUE, -1) === 2147483647) {
console.log("pass")
} else {
console.error("failed")
}
if (divide(100, 6) === 16) {
console.log("pass")
} else {
console.error("failed")
}