【leetcode】592. Fraction Addition and Subtraction
题目如下:
解题思路:本题考察的是分数的加减法。小学时候就学过,分数的加减法是先求两个分母的最小公倍数,然后分子分别乘以最小公倍数与自己分母的商,相加后约分即可。所以,本题只要按+,-两个符号分割输入字符串,就可以得到所有的分数列表,做加减操作即可。考虑到第一个分数是负数的情况,我在代码中加入了一个判断,如果表达式第一个字符是负数,给表达式加上'0/1'的前缀,既不影响结果,又简化了代码。
代码如下:
class Solution(object): def fractionAddition(self, expression): """ :type expression: str :rtype: str """ def gcd(a, b): if a % b == 0: return b else: return gcd(b, a % b) def lcm(a,b): return a * b / gcd(a,b) if expression[0] == '-': expression = '0/1' + expression expression += '#' operators = ['+','-'] operator = '' next = '' res = '' for i in expression: if i in operators or i == '#': if operator == '': operator = i res = next next = '' else: fl = res.split('/') sl = next.split('/') denominator = lcm(int(fl[1]),int(sl[1])) if operator == '+': numerator = int(fl[0]) * denominator/int(fl[1]) + int(sl[0]) * denominator/int(sl[1]) else: numerator = int(fl[0]) * denominator / int(fl[1]) - int(sl[0]) * denominator / int(sl[1]) res = str(numerator) + '/' + str(denominator) next = '' operator = i else: next += i rl = res.split('/') g = gcd(int(rl[0]),int(rl[1])) res = str(int(rl[0])/g) + '/' + str(int(rl[1])/g) return res