Leetcode 592. Fraction Addition and Subtraction
Given a string representing an expression of fractions, you need to add and subtract the fractions and return the result in its simplest form.
The input string will contain fractions separated by a ‘+’ or ‘-‘. Each fraction will be in the form a/b
, where a
and b
are integers. The output should also be a fraction in its simplest form.
Here’s the C++ function to solve this problem:
#include <string>
#include <vector>
#include <sstream>
#include <numeric>
class Solution {
public:
std::string fractionAddition(std::string expression) {
std::vector<int> numerators, denominators;
std::istringstream iss(expression);
char dummy;
int num, denom, first_num, first_denom;
// Parsing the expression and generating numerators and denominators
while (iss >> num >> dummy >> denom) {
numerators.push_back(num);
denominators.push_back(denom);
iss >> dummy;
}
// Find least common denominator (LCD)
int lcm = denominators[0];
for (int d : denominators) {
lcm = lcm / std::gcd(lcm, d) * d;
}
// Adjust numerators to the common denominator
int result_num = 0;
for (int i = 0; i < numerators.size(); ++i) {
result_num += numerators[i] * (lcm / denominators[i]);
}
// Reduce the result fraction
int g = std::gcd(abs(result_num), lcm);
result_num /= g;
lcm /= g;
return std::to_string(result_num) + "/" + std::to_string(lcm);
}
};
n
is the length of the input string.k
is the number of fractions.Overall, the time complexity is primarily O(n + k), which should be efficient for reasonable input sizes according to problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?