166. Fraction to Recurring Decimal Leetcode Python

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".

we need to used a hash table to store current numerator to deal with recurring scenarios. 

code is as follow:

class Solution:
    # @return a string
    def fractionToDecimal(self, numerator, denominator):
        ## denominator can be 0 but do not need to consider here
        if numerator == 0:
            return '0'
        neg = False
        if numerator > 0 and denominator < 0 or numerator < 0 and denominator > 0:
            neg = True
        if numerator % denominator == 0:
            return str(numerator / denominator)
        numerator = abs(numerator)
        denominator = abs(denominator)
        table = {}
        res = ""
        res += str(numerator / denominator)
        res += '.'
        numerator %= denominator
        i = len(res)
        while numerator:
            if numerator not in table:
                table[numerator] = i
            else:
                i = table[numerator]
                res = res[:i] + '(' + res[i:] + ')'
                if neg:
                    return '-' + res
                else:
                    return res
            numerator = numerator * 10
            res += str(numerator/denominator)
            numerator %= denominator
            i+=1
        if neg:
            return '-' + res
        return res


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。