File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
solution/0500-0599/0592.Fraction Addition and Subtraction Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -171,7 +171,52 @@ func gcd(a, b int) int {
171
171
return gcd (b, a%b)
172
172
}
173
173
```
174
+ #### JavaScript
175
+ ``` js
176
+ /**
177
+ * @param {string} expression
178
+ * @return {string}
179
+ */
180
+ var fractionAddition = function (expression ) {
181
+ let x = 0 , y = 1 ;
182
+
183
+ if (! expression .startsWith (' -' ) && ! expression .startsWith (' +' )) {
184
+ expression = ' +' + expression;
185
+ }
186
+
187
+ let i = 0 ;
188
+ const n = expression .length ;
189
+
190
+ while (i < n) {
191
+ const sign = expression[i] === ' -' ? - 1 : 1 ;
192
+ i++ ;
193
+
194
+ let j = i;
195
+ while (j < n && expression[j] !== ' +' && expression[j] !== ' -' ) {
196
+ j++ ;
197
+ }
198
+
199
+ const [a , b ] = expression .slice (i, j).split (' /' ).map (Number );
200
+ x = x * b + sign * a * y;
201
+ y *= b;
202
+ i = j;
203
+ }
204
+
205
+ const gcd = (a , b ) => {
206
+ while (b !== 0 ) {
207
+ [a, b] = [b, a % b];
208
+ }
209
+ return Math .abs (a);
210
+ };
174
211
212
+ const z = gcd (x, y);
213
+ x = Math .floor (x / z);
214
+ y = Math .floor (y / z);
215
+
216
+ return ` ${ x} /${ y} ` ;
217
+ };
218
+
219
+ ```
175
220
<!-- tabs:end -->
176
221
177
222
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments