1. 程式人生 > >[LeetCode] Fraction Addition and Subtraction 分數加減法

[LeetCode] Fraction Addition and Subtraction 分數加減法

Given a string representing an expression of fraction addition and subtraction, you need to return the calculation result in string format. The final result should be irreducible fraction. If your final result is an integer, say 2, you need to change it to the format of fraction that has denominator 1

. So in this case, 2 should be converted to 2/1.

Example 1:

Input:"-1/2+1/2"
Output: "0/1"

Example 2:

Input:"-1/2+1/2+1/3"
Output: "1/3"

Example 3:

Input:"1/3-1/2"
Output: "-1/6"

Example 4:

Input:"5/3+1/3"
Output: "2/1"

Note:

  1. The input string only contains '0' to '9''/''+' and '-'
    . So does the output.
  2. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then '+' will be omitted.
  3. The input only contains valid irreducible fractions, where the numerator and denominator of each fraction will always be in the range [1,10]. If the denominator is 1, it means this fraction is actually an integer in a fraction format defined above.
  4. The number of given fractions will be in the range [1,10].
  5. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.

這道題讓我們做分數的加減法,給了我們一個分數加減法式子的字串,然我們算出結果,結果當然還是用分數表示了。那麼其實這道題主要就是字串的拆分處理,再加上一點中學的數學運算的知識就可以了。這裡我們使用字元流處理類來做,每次按順序讀入一個數字,一個字元,和另一個數字。分別代表了分子,除號,分母。我們初始化分子為0,分母為1,這樣就可以進行任何加減法了。中學數學告訴我們必須將分母變為同一個數,分子才能相加,為了簡便,我們不求最小公倍數,而是直接乘上另一個數的分母,然後相加。不過得到的結果需要化簡一下,我們求出分子分母的最大公約數,記得要取絕對值,然後分子分母分別除以這個最大公約數就是最後的結果了,參見程式碼如下:

class Solution {
public:
    string fractionAddition(string expression) {
        istringstream is(expression);
        int num = 0, dem = 0, A = 0, B = 1; 
        char c;
        while (is >> num >> c >> dem) {
            A = A * dem + num * B;
            B *= dem;
            int g = abs(gcd(A, B));
            A /= g;
            B /= g;
        }
        return to_string(A) + "/" + to_string(B);
    }
    int gcd(int a, int b) {
        return (b == 0) ? a : gcd(b, a % b);
    }
};

參考資料: