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,

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

code is as follow:

class Solution:# @return a stringdef fractionToDecimal(self, numerator, denominator):## denominator can be 0 but do not need to consider hereif numerator == 0:return '0'neg = Falseif numerator > 0 and denominator < 0 or numerator < 0 and denominator > 0:neg = Trueif numerator % denominator == 0:return str(numerator / denominator)numerator = abs(numerator)denominator = abs(denominator)table = {}res = ""res += str(numerator / denominator)res += '.'numerator %= denominatori = len(res)while numerator:if numerator not in table:table[numerator] = ielse:i = table[numerator]res = res[:i] + '(' + res[i:] + ')'if neg:return '-' + reselse:return resnumerator = numerator * 10res += str(numerator/denominator)numerator %= denominatori+=1if neg:return '-' + resreturn res

,天下没有不散的宴席,也许这人间真的只有朦朦胧胧才是真。

166. Fraction to Recurring Decimal Leetcode Python

相关文章:

你感兴趣的文章:

标签云: