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


你可能感兴趣的:(leetcode,string,leetcode,python,hash)