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

• The Solution class itself is just as simple as this:

``````class Solution {
public:
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;
{
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;
}
{
return *this = *this + to_add;
}
operator string() //don't do this in your real life.
{
}
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;
}
};
``````

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