Fraction Addition and Subtraction

Problem Id: 592 Difficulty: Medium


Intuition

Solution


class Solution:
    def fractionAddition(self, expression: str) -> str:
        common = 1
        for i in range(1, 11):
            common *= i

        nums = []
        start = 0
        while start < len(expression):
            mid = expression.index('/', start)
            end = len(expression)
            tmp = expression.find('+', mid)
            if tmp != -1:
                end = min(tmp, end)
            tmp = expression.find('-', mid)
            if tmp != -1:
                end = min(tmp, end)
            numerator = expression[start:mid]
            denominator = expression[mid+1:end]
            nums.append(int(numerator) * common // int(denominator))
            start = end
        numerator = sum(nums)
        denominator = common
        for i in range(2, 11):
            while numerator % i == 0 and denominator % i == 0:
                numerator /= i
                denominator /= i
        return "%d/%d" % (numerator, denominator)