-
Notifications
You must be signed in to change notification settings - Fork 0
/
divide-two-integers.js
66 lines (43 loc) · 1.57 KB
/
divide-two-integers.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
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
var divide = function (dividend, divisor) {
const MAX = 2147483647;
const MIN = -2147483648;
// Check for overflow
if (divisor === 0 || (dividend === MIN && divisor === -1)) {
return MAX;
}
if (divisor === dividend) {
return 1;
}
// Sign of result
const sign = (dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0) ? -1 : 1;
// Quotient
let quotient = 0;
// Take the absolute value
let absoluteDividend = Math.abs(dividend);
let absoluteDivisor = Math.abs(divisor);
// Loop until the dividend is greater than divisor
while (absoluteDividend >= absoluteDivisor) {
// This represents the number of bits shifted or
// how many times we can double the number
let shift = 0;
let shiftedDivisor = absoluteDivisor;
while (absoluteDividend >= shiftedDivisor) {
shift++;
shiftedDivisor = absoluteDivisor << shift;
// To handle overflow using left shift operator in JS
if (shiftedDivisor < 0) {
break;
}
}
// Add the number of times we shifted to the quotient
quotient += (1 << (shift - 1));
// Update the dividend for the next iteration
absoluteDividend -= absoluteDivisor << (shift - 1);
}
return sign === -1 ? -quotient : quotient;
};