File tree 2 files changed +35
-0
lines changed
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change 459
459
589|[ N-ary Tree Preorder Traversal] ( ./0589-n-ary-tree-preorder-traversal.js ) |Easy|
460
460
590|[ N-ary Tree Postorder Traversal] ( ./0590-n-ary-tree-postorder-traversal.js ) |Easy|
461
461
591|[ Tag Validator] ( ./0591-tag-validator.js ) |Hard|
462
+ 592|[ Fraction Addition and Subtraction] ( ./0592-fraction-addition-and-subtraction.js ) |Medium|
462
463
594|[ Longest Harmonious Subsequence] ( ./0594-longest-harmonious-subsequence.js ) |Easy|
463
464
599|[ Minimum Index Sum of Two Lists] ( ./0599-minimum-index-sum-of-two-lists.js ) |Easy|
464
465
605|[ Can Place Flowers] ( ./0605-can-place-flowers.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments