题目:
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:
- The input string only contains
'0'
to'9'
,'/'
,'+'
and'-'
. So does the output. - Each fraction (input and output) has format
±numerator/denominator
. If the first input fraction or the output is positive, then'+'
will be omitted. - 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.
- The number of given fractions will be in the range [1,10].
- The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
思路:
基本思路就是:首先解析出分子序列和分母序列,然后依次相加(如果发现两个分母不一样,则首先通分,然后分子相加)。每次计算完了需要约分,使得分子分母互质(不然容易导致溢出)。最后将分子和分母转换为相应的字符串返回即可。
在实现的过程中我发现istringstream特别好用,可以方便地解析出分子分母,使得代码特别简洁。
代码:
class Solution {
public:
string fractionAddition(string expression) {
istringstream iss(expression);
vector<int> numerators, denominators;
int numerator, denominator;
char c = '/';
while(!iss.eof()) {
iss >> numerator, iss >> c, iss >> denominator;
numerators.push_back(numerator);
denominators.push_back(denominator);
}
numerator = 0, denominator = 1;
int temp_numerator, temp_denominator, temp_gcd;
for (int i = 0; i < numerators.size(); ++i) {
temp_numerator = numerators[i] * denominator;
numerator *= denominators[i];
denominator *= denominators[i];
numerator += temp_numerator;
temp_gcd = gcd(abs(numerator), abs(denominator));
if (temp_gcd > 1) {
numerator /= temp_gcd;
denominator /= temp_gcd;
}
}
return to_string(numerator) + "/" + to_string(denominator);
}
private:
int gcd(int a, int b) { // precondition: both a and b should not be negative
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
};