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 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
166. Fraction to Recurring Decimal Leetcode Python
原文:http://blog.csdn.net/hyperbolechi/article/details/44586747