Fraction Addition and Subtraction - Problem
Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.
The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.
Input & Output
Example 1 — Basic Mixed Operations
$
Input:
expression = "-1/2+1/2+1/3"
›
Output:
"1/3"
💡 Note:
First: -1/2 + 1/2 = 0, then 0 + 1/3 = 1/3. The result is already in irreducible form.
Example 2 — Multiple Fractions
$
Input:
expression = "1/3-1/2"
›
Output:
"-1/6"
💡 Note:
To subtract 1/3 - 1/2, we find common denominator: 2/6 - 3/6 = -1/6
Example 3 — Result is Integer
$
Input:
expression = "1/2+1/2"
›
Output:
"1/1"
💡 Note:
1/2 + 1/2 = 1, which must be expressed as fraction 1/1
Constraints
- The input string only contains '0' to '9', '/', '+' and '-'
- Each fraction is in the form ±numerator/denominator
- Each numerator and denominator is in the range [1, 10]
- The final result should be an irreducible fraction
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code