leetcode592+流式计算一堆分数的结果,字符流操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/82356773

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

class Solution {
public:
    int gcd(int a, int b)
    {
        return (b==0)? a:gcd(b, a%b);
    }
    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);
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/82356773