Skip to content

Commit 2ac21df

Browse files
authored
feat: add solutions to lc problem: No.0592
1 parent 7ee45c4 commit 2ac21df

File tree

1 file changed

+42
-0
lines changed
  • solution/0500-0599/0592.Fraction Addition and Subtraction

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {string} expression
3+
* @return {string}
4+
*/
5+
var fractionAddition = function(expression) {
6+
let x = 0, y = 1;
7+
8+
if (!expression.startsWith('-') && !expression.startsWith('+')) {
9+
expression = '+' + expression;
10+
}
11+
12+
let i = 0;
13+
const n = expression.length;
14+
15+
while (i < n) {
16+
const sign = expression[i] === '-' ? -1 : 1;
17+
i++;
18+
19+
let j = i;
20+
while (j < n && expression[j] !== '+' && expression[j] !== '-') {
21+
j++;
22+
}
23+
24+
const [a, b] = expression.slice(i, j).split('/').map(Number);
25+
x = x * b + sign * a * y;
26+
y *= b;
27+
i = j;
28+
}
29+
30+
const gcd = (a, b) => {
31+
while (b !== 0) {
32+
[a, b] = [b, a % b];
33+
}
34+
return Math.abs(a);
35+
};
36+
37+
const z = gcd(x, y);
38+
x = Math.floor(x / z);
39+
y = Math.floor(y / z);
40+
41+
return `${x}/${y}`;
42+
};

0 commit comments

Comments
 (0)