给定一个表示分数加减运算的字符串 expression
,你需要返回一个字符串形式的计算结果。
这个结果应该是不可约分的分数,即最简分数。 如果最终结果是一个整数,例如 2
,你需要将它转换成分数形式,其分母为 1
。所以在上述例子中, 2
应该被转换为 2/1
。
示例 1:
输入: expression = "-1/2+1/2"
输出: "0/1"
示例 2:
输入: expression = "-1/2+1/2+1/3"
输出: "1/3"
示例 3:
输入: expression = "1/3-1/2"
输出: "-1/6"
提示:
'0'
到 '9'
的数字,以及 '/'
, '+'
和 '-'
。±分子/分母
。如果输入的第一个分数或者输出的分数是正数,则 '+'
会被省略掉。=-
符号将字符串分隔为多个分数运算class Solution:
def fractionAddition(self, expression: str) -> str:
def calc(a: str, b: str, operator: str):
operands = a.split("/")
a1 = int(operands[0])
a2 = int(operands[1])
operands = b.split("/")
b1 = int(operands[0])
b2 = int(operands[1])
b3 = a2*b2
a3 = a1 * b2 + a2*b1 if operator == "+" else a1 * b2 - a2*b1
mod = math.gcd(a3,b3)
a3 //= mod
b3 //= mod
return F"{a3}/{b3}"
if expression[0] == "-": expression = "0/1"+expression
if len(expression) <3: return expression
i = 0
while i < len(expression) and expression[i] not in "+-": i += 1
ret = expression[:i]
while i < len(expression):
start = i
i+=1
while i < len(expression) and expression[i] not in "+-": i += 1
ret = calc(ret, expression[start+1:i], expression[start])
return ret