LC 0166 [M] Fraction to Recurring Decimal - ALawliet/algorithms GitHub Wiki

class Solution:
    def fractionToDecimal2(self, num: int, denom: int) -> str:
        n, remainder = divmod(abs(num), abs(denom))
        sign = '-' if num * denom < 0 else ''
        fraction = [sign + str(n)]
        if remainder == 0:
            return ''.join(fraction)
        fraction.append('.')
        d = {} # remainder to len fraction = position
        # repeating remainder is repeating decimal
        while remainder != 0:
            if remainder in d:
                fraction.insert(d[remainder], '(')
                fraction.append(')')
                break
            d[remainder] = len(fraction) # position
            n, remainder = divmod(remainder * 10, abs(denom))
            fraction.append(str(n))
        return ''.join(fraction)

    def fractionToDecimal(self, numerator, denominator):
        n, remainder = divmod(abs(numerator), abs(denominator))
        sign = '-' if numerator*denominator < 0 else ''
        res = [sign+str(n), '.']
        d = {}

        while remainder > 0 and remainder not in d:
            d[remainder] = len(res)
            n, remainder = divmod(remainder*10, abs(denominator))
            res.append(str(n))
        
        if remainder in d:
            idx = d[remainder]
            res.insert(idx, '(') # insert at start of remainder
            res.append(')')

        return ''.join(res).rstrip(".")