-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAug-23-24.py
41 lines (39 loc) · 1.15 KB
/
Aug-23-24.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def fractionAddition(self, expression: str) -> str:
def gcd(a,b):
while b:
a,b = b,a%b
return abs(a)
if not expression:
return '0/1'
flag = True
temp = ""
fractions = []
for i in expression:
if i=='+' or i=='-':
if temp:
if flag:
fractions.append(temp)
else:
fractions.append('-'+temp)
if i=='+':
flag = True
else:
flag = False
temp = ""
else:
temp += i
if flag:
fractions.append(temp)
else:
fractions.append('-'+temp)
numerator = 0
denominator = 1
for i in fractions:
num,den = map(int,i.split('/'))
numerator = numerator*den + num*denominator
denominator *= den
common = gcd(numerator,denominator)
numerator //= common
denominator //= common
return str(numerator)+'/'+str(denominator)