-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.js
43 lines (35 loc) · 891 Bytes
/
Solution.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
/**
* @param {string} expression
* @return {string}
*/
var fractionAddition = function (expression) {
let x = 0,
y = 1;
if (!expression.startsWith('-') && !expression.startsWith('+')) {
expression = '+' + expression;
}
let i = 0;
const n = expression.length;
while (i < n) {
const sign = expression[i] === '-' ? -1 : 1;
i++;
let j = i;
while (j < n && expression[j] !== '+' && expression[j] !== '-') {
j++;
}
const [a, b] = expression.slice(i, j).split('/').map(Number);
x = x * b + sign * a * y;
y *= b;
i = j;
}
const gcd = (a, b) => {
while (b !== 0) {
[a, b] = [b, a % b];
}
return Math.abs(a);
};
const z = gcd(x, y);
x = Math.floor(x / z);
y = Math.floor(y / z);
return `${x}/${y}`;
};