-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdivide-two-integers.js
More file actions
58 lines (47 loc) · 1.34 KB
/
divide-two-integers.js
File metadata and controls
58 lines (47 loc) · 1.34 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
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Problem: Divide Two Integers
* Link: https://leetcode.com/problems/divide-two-integers/
* Difficulty: Medium
*
* Divide without multiplication, division, or mod operator.
*
* Time Complexity: O(log^2 n)
* Space Complexity: O(1)
*/
// JavaScript Solution - Bit shifting (repeated doubling)
function divide(dividend, divisor) {
const MAX = 2147483647, MIN = -2147483648;
if (dividend === MIN && divisor === -1) return MAX; // overflow case
const negative = (dividend > 0) !== (divisor > 0);
let a = Math.abs(dividend), b = Math.abs(divisor);
let result = 0;
while (a >= b) {
let temp = b, multiple = 1;
// Double the divisor until it exceeds dividend
while (a >= (temp << 1) && (temp << 1) > 0) {
temp <<= 1;
multiple <<= 1;
}
a -= temp;
result += multiple;
}
return negative ? -result : result;
}
module.exports = divide;
/* Python Solution:
def divide(dividend, divisor):
MAX = 2**31 - 1
MIN = -2**31
if dividend == MIN and divisor == -1: return MAX
negative = (dividend > 0) != (divisor > 0)
a, b = abs(dividend), abs(divisor)
result = 0
while a >= b:
temp, multiple = b, 1
while a >= (temp << 1):
temp <<= 1
multiple <<= 1
a -= temp
result += multiple
return -result if negative else result
*/