Skip to content

Commit 675de8a

Browse files
committed
Add solution #592
1 parent 614d201 commit 675de8a

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@
459459
589|[N-ary Tree Preorder Traversal](./0589-n-ary-tree-preorder-traversal.js)|Easy|
460460
590|[N-ary Tree Postorder Traversal](./0590-n-ary-tree-postorder-traversal.js)|Easy|
461461
591|[Tag Validator](./0591-tag-validator.js)|Hard|
462+
592|[Fraction Addition and Subtraction](./0592-fraction-addition-and-subtraction.js)|Medium|
462463
594|[Longest Harmonious Subsequence](./0594-longest-harmonious-subsequence.js)|Easy|
463464
599|[Minimum Index Sum of Two Lists](./0599-minimum-index-sum-of-two-lists.js)|Easy|
464465
605|[Can Place Flowers](./0605-can-place-flowers.js)|Easy|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 592. Fraction Addition and Subtraction
3+
* https://leetcode.com/problems/fraction-addition-and-subtraction/
4+
* Difficulty: Medium
5+
*
6+
* Given a string expression representing an expression of fraction addition and subtraction,
7+
* return the calculation result in string format.
8+
*
9+
* The final result should be an irreducible fraction. If your final result is an integer,
10+
* change it to the format of a fraction that has a denominator 1. So in this case, 2 should
11+
* be converted to 2/1.
12+
*/
13+
14+
/**
15+
* @param {string} expression
16+
* @return {string}
17+
*/
18+
var fractionAddition = function(expression) {
19+
const gcdCalc = (a, b) => b === 0 ? a : gcdCalc(b, a % b);
20+
const fractions = expression.match(/[+-]?\d+\/\d+/g);
21+
let n = 0;
22+
let d = 1;
23+
24+
for (const fraction of fractions) {
25+
const [numerator, denominator] = fraction.split('/').map(Number);
26+
n = n * denominator + numerator * d;
27+
d = d * denominator;
28+
const gcd = Math.abs(gcdCalc(n, d));
29+
n /= gcd;
30+
d /= gcd;
31+
}
32+
33+
return `${n}/${d}`;
34+
};

0 commit comments

Comments
 (0)