-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0029-divide-two-integers.js
More file actions
45 lines (34 loc) · 1.3 KB
/
0029-divide-two-integers.js
File metadata and controls
45 lines (34 loc) · 1.3 KB
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
/**
* Divide Two Integers
* Time Complexity: O(log N)
* Space Complexity: O(1)
*/
var divide = function (dividend, divisor) {
const MAXIMUM_POS_INTEGER = 2147483647;
const MINIMUM_NEG_INTEGER = -2147483648;
if (dividend === MINIMUM_NEG_INTEGER && divisor === -1) {
return MAXIMUM_POS_INTEGER;
}
let isFinalResultNegative = (dividend < 0) !== (divisor < 0);
let currentWorkingDividend = Math.abs(dividend);
let currentWorkingDivisor = Math.abs(divisor);
if (currentWorkingDividend < currentWorkingDivisor) {
return 0;
}
let overallQuotientSum = 0;
while (currentWorkingDividend >= currentWorkingDivisor) {
let partialDivisorChunk = currentWorkingDivisor;
let partialQuotientChunk = 1;
while (currentWorkingDividend - partialDivisorChunk >= partialDivisorChunk) {
partialDivisorChunk += partialDivisorChunk;
partialQuotientChunk += partialQuotientChunk;
}
currentWorkingDividend -= partialDivisorChunk;
overallQuotientSum += partialQuotientChunk;
}
let finalCalculatedQuotient = isFinalResultNegative ? -overallQuotientSum : overallQuotientSum;
if (finalCalculatedQuotient > MAXIMUM_POS_INTEGER) {
return MAXIMUM_POS_INTEGER;
}
return finalCalculatedQuotient;
};