1. 程式人生 > >[Math_Medium] 592. Fraction Addition and Subtraction

[Math_Medium] 592. Fraction Addition and Subtraction

n) problems 都是 public https ngs addition 字符串 ref

原題:592. Fraction Addition and Subtraction

題目大意:

給出一個分數字符串式子(分子分母都是1~10),求其和

解題思路:

利用stringstream,它可以自動地實現字符串和數字之間的轉換,比如 -1/2,可以輸出為-1,/,2,把每個數取出來後就通分進行計算

代碼:

class Solution{
    public:
    int gcd(int a,int b)
    {
        int c=0;
        while(b)
        {
            c=a%b;
            a=b;
            b=c;
        }
        return a;
    }
    string fractionAddition(string expression) {
        stringstream  s(expression);
        int a1=0,b1=0,a2=0,b2=0,temp=0,k=0;
        char c;
        s>>b1;//分子
        s>>c;//符號
        s>>a1;//分母
        while(s>>b2)
        {
            s>>c;
            s>>a2;
            temp=gcd(a1,a2);
            k=a1;
            a1=a1*a2/temp;
            b1=b1*(a1/k)+b2*(a1/a2);
            temp=gcd(a1,abs(b1));//註意分母不會為負數,只有分子為負數,所以確保最大公約數為正數,需要取絕對值
            a1/=temp;
            b1/=temp;
        }
        return to_string(b1)+"/"+to_string(a1);
    }
};

以上

[Math_Medium] 592. Fraction Addition and Subtraction