LeetCode Fraction Addition and Subtraction

LeetCode Fraction Addition and Subtraction

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.

给定一个只包含+-/的运算字符串,要求求出这个字符串的值,并且用最简分数的形式表示。

参考这篇博客,没什么技巧,就是用代码模拟手算的过程。首先求出所有分母的最小公倍数,然后通分,使得所有数的分母都相同,最后把所有通分过的分子加起来,得到结果。最最后一步就是把分子和分母约分。

这些步骤中涉及到求最小公倍数和最大公约数。最大公约数的求法gcd是必须掌握的,另外再根据gcd(x,y)*lcm(x,y)=x*y的性质,可以求到最小公倍数lcm(x,y)

代码如下:

class Solution {
private:
	int gcd(int x, int y) {
		while (y) {
			int tmp = x % y;
			x = y;
			y = tmp;
		}
		return x;
	}
	int lcm(int x, int y) {
		return x * y / gcd(x, y);
	}
public:
	string fractionAddition(string expression) {
		vector<int> num, denom; // 分子,分母
		expression += "+"; // 哨兵
		int i = 0, j = 0;
		bool isnum = true;
		for (j = 0; j < expression.size(); ++j) {
			if (j != 0 && (expression[j] == '/' || expression[j] == '-' || expression[j] == '+')) {
				int one = atoi(expression.substr(i, j - i).c_str());

				if (isnum)num.push_back(one);
				else denom.push_back(one);

				isnum = !isnum;

				if (expression[j] == '/') i = j + 1;
				else i = j;
			}
		}
		
		int fm = 1;
		for (int i = 0; i < denom.size(); ++i)fm = lcm(fm, denom[i]);
		int fz = 0;
		for (int i = 0; i < num.size(); ++i)fz += num[i] * (fm / denom[i]);
		int g = 0;
		if (fz < 0)
			g = gcd(-fz, fm);
		else
			g = gcd(fz, fm);
		return to_string(fz / g) + "/" + to_string(fm / g);
	}
};

本代码提交AC,用时3MS。

Leave a Reply

Your email address will not be published. Required fields are marked *