Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/08/23 13:39), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串758/1548 (看更多)
592. Fraction Addition and Subtraction ## 思路 n1/d1 +n2/d2 -n3/d3 = (n1/d1) + (n2/d2) + (-n3/d3) (n1/d1) + (n2/d2) = (n1*d2 + n2*d1) / (d1 * d2) 先parse每個fraction pair並做相加, 最後再把分子分母除gcd ## Code ```python class Solution: def fractionAddition(self, expression: str) -> str: n = len(expression) i = 0 def get_num(): nonlocal i is_neg = False if expression[i] == '+': i += 1 if expression[i] == '-': is_neg = True i += 1 num = 0 while i < n and expression[i].isdigit(): num = num * 10 + int(expression[i]) i += 1 return -num if is_neg else num def get_gcd(a, b): while b: a, b = b, a % b return a curr_num, curr_deno = 0, 1 while i < n: num = get_num() i += 1 # `/` deno = get_num() # (n1/d1) + (n2/d2) = (n1*d2 + n2*d1) / (d1 * d2) curr_num = curr_num * deno + num * curr_deno curr_deno = curr_deno * deno if curr_num == 0: return '0/1' gcd = get_gcd(curr_num, curr_deno) return f'{curr_num//gcd}/{curr_deno//gcd}' ``` -- http://i.imgur.com/OLvBn3b.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.179 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1724391586.A.814.html
文章代碼(AID): #1co22YWK (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1co22YWK (Marginalman)