LeetCode 166. Fraction to Recurring Decimal
考点 | 难度 |
---|---|
Hash Map | Medium |
题目
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104 for all the given inputs.
思路
用hash map判断remainder是否重复。如果重复就在index的位置上insert括号。最后一行排除了类似"2.(0)"的情况。
答案
class Solution:
def fractionToDecimal(self, numerator, denominator):
n, remainder = divmod(abs(numerator), abs(denominator))
sign = '-' if numerat