---
# System prepended metadata

title: 592. Fraction Addition and Subtraction
tags: [C++, LeetCode]

---

# LeetCode 592. Fraction Addition and Subtraction

https://leetcode.com/problems/fraction-addition-and-subtraction/description/

## 題目大意

給定字串表達分數加減，以字串形式回傳答案
答案應為最簡分數，若為整數則表達為分母為 $1$

## 思考

就是分數運算而已，通分再化簡

$$
\frac{A}{B} + \frac{a}{b} = \frac{Ab + Ba}{Bb} = \frac{A'}{B'}
$$

之後再同除以 GCD 化簡

```cpp!
class Solution
{
public:
    string fractionAddition(string expression)
    {
        istringstream iss(expression);
        char c;
        int a, b, A = 0, B = 1;

        while (iss >> a >> c >> b)
        {
            A = A * b + B * a;
            B *= b;
            const int n = abs(__gcd(A, B));
            A /= n;
            B /= n;
        }

        return to_string(A) + "/" + to_string(B);
    }
};
```