Skip to content

Commit 2f84e7f

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

File tree

1 file changed

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

1 file changed

+45
-0
lines changed

solution/0500-0599/0592.Fraction Addition and Subtraction/README_EN.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,52 @@ func gcd(a, b int) int {
171171
return gcd(b, a%b)
172172
}
173173
```
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+
};
174211

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+
```
175220
<!-- tabs:end -->
176221

177222
<!-- solution:end -->

0 commit comments

Comments
 (0)