未验证 提交 3324fdb3 编写于 作者: K KEQI HUANG 提交者: GitHub

Create 166._

上级 8d471ad2
### 166. Fraction to Recurring Decimal
题目:
<https://leetcode.com/problems/fraction-to-recurring-decima/>
难度:
Medium
```python
class Solution:
# @return a string
def fractionToDecimal(self, n, d):
res = ''
if n == 0: # zero numerator
return str(n)
if (n < 0) ^ (d < 0): # determine the sign
res += '-'
n = abs(n) # remove sign of operands
d = abs(d)
res += str(n / d) # append integral part
if (n % d == 0): # in case no fractional part
return res
res += '.'
r = n % d
m = {}
while r: # simulate the division process
if r in m: # meet a known remainder
res = res[:m[r]] + '(' + res[m[r]:] + ')' # so we reach the end of the repeating part
break
m[r] = len(res) # if the remainder is first seen, remember the current position for it
r *= 10
res += str(r / d) # append the quotient digit
r %= d
return res
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册