Clear C++ Solution By Implementing a Standard Fraction Class.


  • 0
    F

    The Solution class itself is just as simple as this:

    class Solution {
    public:
        string fractionAddition(string expression) {
            stringstream ss(expression);
            Fraction sum {0, 1}, frac;
            while (ss >> frac)
                sum += frac;
            return sum;
        }
    };
    

    All works are done here:

    class Fraction
    {
        static int gcd(int a, int b)
        {
            int r = a % b;
            while(r)
                a = b, b = r,  r = a % b;
            return b;
        }
        void reduce()
        {
            int p = abs(gcd(num, denom));
            num /= p;
            denom /= p;
        }
    public:
        int num, denom;
        Fraction operator+(Fraction to_add) const
        {
            int p = gcd(denom, to_add.denom);
            long long q = denom / p * to_add.denom;
            int m1 = q / denom, m2 = q / to_add.denom;
            Fraction result {m1 * num + m2 * to_add.num, q};
            result.reduce();
            return result;
        }
        Fraction & operator+=(Fraction to_add)
        {
            return *this = *this + to_add;
        }
        operator string() //don't do this in your real life.
        {
            return to_string(num) + '/' + to_string(denom);
        }
        friend istream & operator>>(istream &is, Fraction & frac)
        {
            char c = '+';
            if (!isdigit(is.peek()))
                is >> c;
            int sign = c == '+' ? 1 : -1;
            is >> frac.num >> c >> frac.denom;
            frac.num *= sign;
            return is;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.