-
Notifications
You must be signed in to change notification settings - Fork 0
/
29. 两数相除-MEDIUM.js
74 lines (71 loc) · 1.84 KB
/
29. 两数相除-MEDIUM.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
// https://leetcode.cn/problems/divide-two-integers/
/**
* @param {number} dividend
* @param {number} divisor
* @return {number}
*/
const paramDividend = 2;
const paramDivisor = 2;
/**
* 迭代法
*/
var divide = function (dividend, divisor) {
const MAX = 2147483647; // 2^31-1
const MIN = -2147483648; // -2^31
if (dividend == 0) return 0;
if (divisor == 0) return null;
if (divisor == 1) return dividend;
if (divisor == -1) return dividend <= MIN ? MAX : -dividend;
let minus = false; // 是否是负数
// dividend, divisor都处理成负数计算
if (dividend > 0) {
dividend = -dividend;
minus = !minus;
}
if (divisor > 0) {
divisor = -divisor;
minus = !minus;
}
let quotient = 0;
while (dividend <= divisor) {
dividend -= divisor;
quotient++;
}
return minus ? -quotient : quotient;
};
console.log(divide(paramDividend, paramDivisor));
/**
* 类二分
* 与迭代法的区别就在于优化迭代的步数
*/
var divide = function (dividend, divisor) {
const MAX = 2147483647; // 2^31-1
const MIN = -2147483648; // -2^31
if (dividend == 0) return 0;
if (divisor == 0) return null;
if (divisor == 1) return dividend;
if (divisor == -1) return dividend <= MIN ? MAX : -dividend;
let minus = false; // 是否是负数
// dividend, divisor都处理成负数计算
if (dividend > 0) {
dividend = -dividend;
minus = !minus;
}
if (divisor > 0) {
divisor = -divisor;
minus = !minus;
}
let quotient = 0;
while (dividend <= divisor) {
let tempQuotient = 1;
let tempDivisor = divisor;
while (dividend <= tempDivisor + tempDivisor) {
tempDivisor += tempDivisor;
tempQuotient += tempQuotient;
}
dividend -= tempDivisor;
quotient += tempQuotient;
}
return minus ? -quotient : quotient;
};
console.log(divide(paramDividend, paramDivisor));