Skip to content

Latest commit

 

History

History
61 lines (42 loc) · 1.65 KB

_166. Fraction to Recurring Decimal.md

File metadata and controls

61 lines (42 loc) · 1.65 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : May 31, 2024

Last updated : July 01, 2024


Related Topics : Hash Table, Math, String

Acceptance Rate : 25.22 %


Solutions

Python

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        pastDivs = dict()
        outputs = []

        if numerator == 0 :
            return '0'

        if ((numerator < 0) ^ (denominator < 0)) :
            outputs.append('-')
        
        numerator, denominator = abs(numerator), abs(denominator)

        outputs.append(str(numerator // denominator))
        numerator = (numerator % denominator) * 10
        if numerator == 0 :
            return ''.join(outputs)

        outputs.append('.')

        # Note: denominator will never chance ==> dict can be based on numerator
        while not numerator in pastDivs.keys() :
            if numerator == 0 :
                return ''.join(outputs)

            pastDivs[numerator] = len(outputs)
            outputs.append(str(numerator // denominator))
            numerator = (numerator % denominator) * 10            


        outputs.append(')')
        return ''.join(outputs[0:pastDivs.get(numerator)]) + '(' + \
               ''.join(outputs[pastDivs.get(numerator):])