Problem statement

https://leetcode.com/problems/equal-rational-numbers/

Solution

What we need to do in our problem is to parse our number and we can have several parts: a is integer part, b is preperiod and c is period. Then we need to create rational number from this values. Imagine that c = 13, than in fact it is fraction 13/99. Then we need to do some math to calculate full fraction. In the end compare fractions.

Complexity

It is O(n + m) for time and space, where n and m are lengths of S and T.

Code

class Solution:
    def isRationalEqual(self, S, T):
        def MakeRat(S):
            b, c = "", ""
            if "." not in S: 
                a = S
            else:
                a, b = S.split(".")
                if "(" in S:
                    b, c = b.split("(")
                    c = c[:-1]
        
            l1, l2 = len(b), len(c)
            if b == "": b = "0"
            if c == "": c = "0"
            a, b, c = int(a), int(b), int(c)
            P2 = 10**l2 - 1 if l2 > 0 else 1
            
            return (a*10**l1*P2 + b*P2 + c, 10**l1*P2)
        
        (x1, y1), (x2, y2) = MakeRat(S), MakeRat(T)

        return x1*y2 == x2*y1