Similar Problems

Similar Problems not available

Fraction Addition And Subtraction - Leetcode Solution

Companies:

LeetCode:  Fraction Addition And Subtraction Leetcode Solution

Difficulty: Medium

Topics: math string simulation  

Fraction Addition and Subtraction is a problem on LeetCode that requires the addition and subtraction of fractions. The problem statement is as follows:

Given a string expression representing an arithmetic operation of fractions, return the result of the operation in string format.

The expression consists of two fractions separated by either "+" or "-". Each fraction is in the format "numerator/denominator" where both numerator and denominator are integers. The result should be in the same format as the input.

Example 1:

Input: expression = "1/3-1/2" Output: "-1/6" Explanation: The result is (-1/3) + (-1/2) = -5/6, which is equal to -1/6 in fractional form.

To solve the problem, we can follow the below steps:

  1. Split the input string into two fractions separated by either "+" or "-".

  2. Parse each fraction into numerator and denominator.

  3. Find the common denominator of the two fractions.

  4. Add or subtract the numerators of the fractions depending on the operation sign and return the result in fractional form.

Here is the Python code for the above logic:

def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def fractionAddition(expression: str) -> str:
    # Split the input string into two fractions separated by either "+" or "-"
    split_expr = expression.split("+") if "+" in expression else expression.split("-")
    # Parse each fraction into numerator and denominator
    num1, den1 = split_expr[0].split("/")
    num2, den2 = split_expr[1].split("/")
    # Convert the numerator and denominator into integers
    num1, den1, num2, den2 = int(num1), int(den1), int(num2), int(den2)
    # Find the common denominator of the two fractions
    lcm = (den1 * den2) // gcd(den1, den2)
    # Add or subtract the numerators of the fractions depending on the operation sign
    if "+" in expression:
        num = (num1 * (lcm // den1)) + (num2 * (lcm // den2))
    else:
        num = (num1 * (lcm // den1)) - (num2 * (lcm // den2))
    # Reduce the fraction to its simplest form
    g = gcd(num, lcm)
    num, den = num // g, lcm // g
    # Return the result in fractional form
    return str(num) + "/" + str(den)

The above code will solve the Fraction Addition and Subtraction problem on LeetCode.

Fraction Addition And Subtraction Solution Code

1