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