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:
1. The input string only contains ‘0’ to ‘9’, ‘/’, ‘+’ and ‘-‘. So does the output.
2. Each fraction (input and output) has format ±numerator/denominator. If the first input fraction or the output is positive, then ‘+’ will be omitted.
3. 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.
4. The number of given fractions will be in the range [1,10].
5. The numerator and denominator of the final result are guaranteed to be valid and in the range of 32-bit int.
自己实现的算法思路上很简单,但是代码量比较大,需要优化,注意最后需要对分子和分母进行求最大公约数这一步,以确保所得到的分数没有最大公约数;
vector<int> suanshi(string expression, int& i){
vector<int> data(2, 0);
while (i < expression.size() && expression[i] >= '0' && expression[i] <= '9')
data[0] = data[0] * 10 + expression[i] - '0', i++;
i++;
while (i < expression.size() && expression[i] >= '0' && expression[i] <= '9')
data[1] = data[1] * 10 + expression[i] - '0', i++;
return data;
}
string fractionAddition(string expression) {
if (expression == "")return "";
vector<int> data(2, 0);
int i = 0;
bool flag = false;
if (expression[i] == '-')i++, flag = true;
while (expression[i] != '/')
data[0] = data[0] * 10 + expression[i] - '0', i++;
if (flag)data[0] = -data[0];
i++;
while (expression[i] >= '0' && expression[i] <= '9')
data[1] = data[1] * 10 + expression[i] - '0', i++;
for (; i < expression.size(); ){
char ch = expression[i++];
vector<int> temp = suanshi(expression, i);
if (data[1] != temp[1]){
temp[0] = temp[0] * data[1];
data[0] = data[0] * temp[1];
data[1] = data[1] * temp[1];
}
if (ch == '+') data[0] = data[0] + temp[0];
else if (ch == '-')data[0] = data[0] - temp[0];
if (data[0] == 0)data[1] = 1;
}
if (data[0] % data[1] == 0){
data[0] /= data[1];
data[1] = 1;
ostringstream out;
out << data[0] << '/' << data[1];
return out.str();
}
//辗转相除法
int x = data[0], y = data[1];
while (y != 0){
int p = y;
y = x % y;
x = p;
}
if (x < 0)x = -x;
data[0] /= x;
data[1] /= x;
ostringstream out;
out << data[0] << '/' << data[1];
return out.str();
}