Simulator long division process to calculate fraction result.
Because the same numerator always leads to the same fraction result.
Use hash table to save numerator encountered to avoid repeating fractional part.
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
negative = (numerator < 0) ^ (denominator < 0)
numerator = abs(numerator)
denominator = abs(denominator)
result = str(numerator // denominator)
if numerator % denominator == 0:
return "-" + result if negative and numerator != 0 else result
numerator = numerator % denominator
numerator *= 10
visited = {}
result += "."
while numerator > 0:
if numerator not in visited:
visited[numerator] = len(result)
else:
prefix = result[:visited[numerator]] + '('
appendix = result[visited[numerator]:] + ')'
result = prefix + appendix
break
if numerator > denominator:
result += str(numerator // denominator)
numerator = numerator % denominator
else:
result += '0'
numerator *= 10
return "-" + result if negative else result
Edited on 03/04/2021. A simpler implementation.
No comments:
Post a Comment