# M-166. Fraction to Recurring Decimal

{% embed url="<https://leetcode.com/problems/fraction-to-recurring-decimal/>" %}

```python
# 其实思路很好懂, 就是一些细节要注意
class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        is_neg = True if numerator * denominator < 0 else False
        n, r = divmod(abs(numerator), abs(denominator))
        s = str(n)
        if is_neg:
            s = '-' + s
        if r:
            s += '.'
        pos = len(s)
        
        r_mapping = {r : pos}
        
        while r:
        # 注意这里是用10*abs(r)做被除数了
            n, r = divmod(10*abs(r), abs(denominator))
            s += str(n)
            if r in r_mapping:
                return s[:r_mapping[r]] + "(" + s[r_mapping[r]: ]+ ")"
            pos += 1
            r_mapping[r] = pos
            
        return s
```
