using python fractions library


  • 0
    from fractions import Fraction
    class Solution(object):
        def fractionAddition(self, expression):
            """
            :type expression: str
            :rtype: str
            """
            res = Fraction(0)
            end = len(expression)
            for i in xrange(len(expression)-1, -1, -1):
                if expression[i] == "-":
                    res -= Fraction(expression[i+1:end])
                    end = i
                if expression[i] == "+":
                    res += Fraction(expression[i+1:end])
                    end = i
            if expression[0] != "-":
                res += Fraction(expression[:end])
            return str(res.numerator) + "/" + str(res.denominator)
    
    # using fractions library is somehow making this problem meaningless, try to do it using gcd or lcm

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.