our task is to find the sum of two fractions, expr...
创建于:2025年6月23日
创建于:2025年6月23日
our task is to find the sum of two fractions, expressed in the form
X
/
Y
X/Y and
U
/
V
U/V, where
X
X,
Y
Y,
U
U, and
V
V are four integers. Compute their sum and reduce it to its lowest indivisible state:
A
/
B
A/B.
For example:
2
/
6
+
2
/
6
2/6+2/6 equals
4
/
6
4/6, which should be reduced to
2
/
3
2/3.
7
/
10
+
13
/
10
7/10+13/10 equals
20
/
10
20/10 which should be reduced to
2
/
1
2/1.
You are given an array of strings, which contains several expressions in the form "X/Y+U/V". Return a string array, where the
i
i-th element is the result for the
i
i-th expression in the form "A/B".
Example
For fractions = ["2/6+2/6", "7/10+13/10"], the output should be solution(fractions) = ["2/3", "2/1"]
in c++ without comments
cpp#include <bits/stdc++.h> using namespace std; vector<string> solution(const vector<string>& fractions) { vector<string> res; for (const string& expr : fractions) { size_t a = expr.find('/'); size_t b = expr.find('+', a); size_t c = expr.find('/', b); long long X = stoll(expr.substr(0, a)); long long Y = stoll(expr.substr(a + 1, b - a - 1)); long long U = stoll(expr.substr(b + 1, c - b - 1)); long long V = stoll(expr.substr(c + 1)); long long num = X * V + U * Y; long long den = Y * V; long long g = std::gcd(num, den); res.push_back(to_string(num / g) + "/" + to_string(den / g)); } return res; }