http://bookshadow.com/weblog/2017/05/21/leetcode-fraction-addition-and-subtraction/
题目大意:
求分数加减法算式的值,结果化为最简分数。
注意:
- 输入字符串只包含0~9,+-/。输出亦然
- 每个分数之前包含±号,若第一个分数为正数,省去+
- 输入只包含有效的最简分数,分子分母范围[1, 10]。若分母为1,表示该分数实际上是一个整数。
- 分数的个数范围[1, 10]
- 分子分母的结果在32位带符号整数范围之内
解题思路:
def gcd(a, b):
if a < b: a, b = b, a
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b / gcd(a, b)
part = ''
fractions = []
for c in expression:
if c in '+-':
if part: fractions.append(part)
part = ''
part += c
if part: fractions.append(part)
hi = [int(e.split('/')[0]) for e in fractions]
lo = [int(e.split('/')[1]) for e in fractions]
LO = reduce(lcm, lo)
HI = sum(h * LO / l for h, l in zip(hi, lo))
GCD = abs(gcd(LO, HI))
return '%s/%s' % (HI / GCD, LO / GCD)
if a < b: a, b = b, a
while b:
a, b = b, a % b
return a
def lcm(a, b):
return a * b / gcd(a, b)
part = ''
fractions = []
for c in expression:
if c in '+-':
if part: fractions.append(part)
part = ''
part += c
if part: fractions.append(part)
hi = [int(e.split('/')[0]) for e in fractions]
lo = [int(e.split('/')[1]) for e in fractions]
LO = reduce(lcm, lo)
HI = sum(h * LO / l for h, l in zip(hi, lo))
GCD = abs(gcd(LO, HI))
return '%s/%s' % (HI / GCD, LO / GCD)