
Problem Statement
The task is to take a string input named expression
that describes a mathematical operation involving the addition and subtraction of fractions and possibly integers represented as fractions (e.g., 2
expressed as 2/1
). This string should then be processed to perform the described operations and produce a result, which will also be a string. The resultant fraction should be simplified to its irreducible form, meaning no further reduction is possible. If the result is an integer, it should be formatted as a fraction with the integer as the numerator and 1
as the denominator.
Examples
Example 1
Input:
expression = "-1/2+1/2"
Output:
"0/1"
Example 2
Input:
expression = "-1/2+1/2+1/3"
Output:
"1/3"
Example 3
Input:
expression = "1/3-1/2"
Output:
"-1/6"
Constraints
- The input string only contains
'0'
to'9'
,'/'
,'+'
and'-'
. So does the output. - Each fraction (input and output) has the 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 is1
, 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.
Approach and Intuition
To solve the problem laid out in the problem statement, follow these high-level steps:
Parsing the Input Expression:
Start by extracting each fraction from the given expression string. Since the fractions are guaranteed to be correctly formatted and only contain valid characters ([0-9]
,/
,+
,-
), they can be directly processed using regular expressions or string splitting techniques.Fraction Operations:
Calculate the result of the series of additions and subtractions by iterating over the extracted fraction elements. Implement handling for both operations:- Addition of Fractions: To add fractions, adjust both to a common denominator (typically the product of their denominators), sum the adjusted numerators, and keep the common denominator.
- Subtraction of Fractions: This is similar to addition, except subtract the second numerator from the first after adjusting for a common denominator.
Simplifying the Result: Once the combined fraction is obtained, simplify it by dividing both the numerator and the denominator by their greatest common divisor (GCD). This ensures the result is in its irreducible form.
Formatting the Result:
If the resulting fraction has a denominator of1
, then represent it as mentioned in the problem statement, with the format ofnumerator/1
.Edge Cases:
Handle special cases like:- Operations result in a negative fraction.
- The fraction reduces to zero (result should be
0/1
).
By following these steps, each fraction operation can be computed efficiently and systematically, while ensuring the mathematical correctness and the specific format requirements as per the problem constraints.
Solutions
- C++
- Java
- Python
class Solution {
public:
string fractionSum(string fracExp) {
int numerator = 0;
int denominator = 1;
// Divide expression into individual fractions
vector<string> fractionParts;
int start = 0;
if (fracExp[0] != '-') fracExp = '+' + fracExp;
while (start < fracExp.size()) {
int end = start + 1;
while (end < fracExp.size() && fracExp[end] != '+' && fracExp[end] != '-') {
end++;
}
fractionParts.push_back(fracExp.substr(start, end - start));
start = end;
}
for (string frac : fractionParts) {
size_t divider = frac.find('/');
int numeratorPart = stoi(frac.substr(1, divider - 1));
if (frac[0] == '-') numeratorPart *= -1;
int denominatorPart = stoi(frac.substr(divider + 1));
numerator = numerator * denominatorPart + numeratorPart * denominator;
denominator = denominator * denominatorPart;
int commonDivisor = abs(calculateGCD(numerator, denominator));
numerator /= commonDivisor;
denominator /= commonDivisor;
}
return to_string(numerator) + "/" + to_string(denominator);
}
private:
int calculateGCD(int x, int y) {
if (x == 0) return y;
return calculateGCD(y % x, x);
}
};
The provided C++ solution is designed to handle the task of adding and subtracting fractions given in a single string expression. The function fractionSum
takes as input a string that represents a series of fractions connected by '+' or '-' signs and returns the result as a simplified fraction in string format.
- Begin by initializing the
numerator
to 0 anddenominator
to 1. - Prepare the fraction expression for processing by adding a '+' before it if it does not begin with a '-'. This standardizes the input for easy splitting.
- Split the entire expression into individual fraction strings. This involves iterating over characters of
fracExp
and using the signs '+' or '-' as delimiters. - For each fraction string:
- Identify the location of the '/' to split the fraction into numerator and denominator parts.
- Convert these parts from string to integers. Additionally, handle the sign of the numerator based on the first character of the fraction part.
- Perform the fraction addition/subtraction operation using the formula:
numerator = numerator * denominatorPart + numeratorPart * denominator
, and adjust the common denominator accordingly. - Simplify the resulting fraction by calculating the greatest common divisor (GCD) of the numerator and the denominator, then dividing both by this GCD.
- The helper function
calculateGCD
uses recursion to find the GCD, enhancing the simplification step. - Finally, construct the simplified fraction as a string in the format
numerator/denominator
and return it.
Implement this approach to effectively manage fraction operations within a single expression, utilizing arithmetic principles and GCD for simplification.
class Solution {
public String fractionAddition(String expression) {
int numerator = 0;
int denominator = 1;
String[] fractions = expression.split("/|(?=[-+])");
for (int idx = 0; idx < fractions.length; idx += 2) {
int partNumerator = Integer.parseInt(fractions[idx]);
int partDenominator = Integer.parseInt(fractions[idx + 1]);
numerator = numerator * partDenominator + partNumerator * denominator;
denominator = denominator * partDenominator;
}
int gcdValue = Math.abs(computeGCD(numerator, denominator));
numerator /= gcdValue;
denominator /= gcdValue;
return numerator + "/" + denominator;
}
private int computeGCD(int x, int y) {
if (x == 0) return y;
return computeGCD(y % x, x);
}
}
The Java program provided addresses the problem of performing fraction addition and subtraction given a string expression. It effectively parses and computes the result of operations involving fractions. The approach involves:
- Initializing a starting
numerator
of 0 anddenominator
of 1. - Splitting the input string into individual fractions using a combination of denominator symbol ("/") and a lookahead for signs ("+" or "-") to handle the parsing appropriately.
- Iterating through the parsed fractions:
- Convert string representations of the numerators and denominators into integers.
- Update the
numerator
using the cross multiplication formula to perform the addition or subtraction. - Simultaneously update the
denominator
by multiplying the denominators of the current result and the current fraction.
- Once all fractions are processed, simplify the final fraction:
- Calculate the greatest common divisor (GCD) of the
numerator
anddenominator
. - Divide both the
numerator
anddenominator
by their GCD to simplify the fraction.
- Calculate the greatest common divisor (GCD) of the
- The function then returns the simplified fraction as a string.
This solution ensures that the output is always in its simplest form and correctly handles both addition and subtraction of multiple fractions.
import re
class Calculator:
def sumFractions(self, input_string: str) -> str:
current_numerator = 0
current_denominator = 1
parsed_numbers = re.split("/|(?=[-+])", input_string)
parsed_numbers = list(filter(None, parsed_numbers))
for index in range(0, len(parsed_numbers), 2):
numerator = int(parsed_numbers[index])
denominator = int(parsed_numbers[index + 1])
current_numerator = current_numerator * denominator + numerator * current_denominator
current_denominator = current_denominator * denominator
greatest_common_divisor = abs(self.findGCD(current_numerator, current_denominator))
current_numerator //= greatest_common_divisor
current_denominator //= greatest_common_divisor
return f"{current_numerator}/{current_denominator}"
def findGCD(self, x: int, y: int) -> int:
if x == 0:
return y
return self.findGCD(y % x, x)
The provided Python code defines a class Calculator
that offers functionality to add and subtract fractions given as a string. Implement the sumFractions
method that parses the input string of fractions, performs the mathematical operations, and returns the result in its simplest form.
- Start by importing the
re
library, which helps in parsing the input string using regular expressions to correctly identify the components of fractions. - Initialize a numerator and denominator to store cumulative results.
- Split the input string into parts that represent individual numerators and denominators, handling both positive and negative fractions.
- Iterate through these parts. For each fraction, convert the numerator and denominator into integers.
- Use these integers to update the
current_numerator
andcurrent_denominator
by applying the operations of fractional addition or subtraction. - After processing all fractions, simplify the resulting fraction. Use the helper method
findGCD
to find the greatest common divisor of the numerator and denominator, then divide both by this value to simplify the fraction. - Return the simplified fraction as a string.
The findGCD
method employs a recursive approach to compute the greatest common divisor, essential for simplifying the fraction.
The solution ensures the final output is in the reduced form, making use of arithmetic operations and the Euclidean algorithm for computing the greatest common divisor. By maintaining accuracy in the operations and ensuring proper input parsing, the code effectively handles both addition and subtraction of multiple fractions seamlessly.
No comments yet.