Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution(object):
- def fractionToDecimal(self, n, d):
- """
- :type numerator: int
- :type denominator: int
- :rtype: str
- """
- #排除分子是0 或者 分子与分母相等的情况
- if n == 0:
- return "0"
- if n == d:
- return "1"
- # 确定符号
- sign = ""
- if (n > 0) ^ (d > 0):
- sign = "-"
- n = abs(n)
- d = abs(d)
- #开始计算
- if d == 1:
- res = str(n)
- else:
- q, r, idx = 0, 0, 0
- remainder = {} # <key, value> => <余数, 余数所对应的商在decimal中的index>
- decimal = []
- if n > d:
- q = n // d
- r = n % d
- else:
- r = n % d
- # 当余数重复以后商也开始重复
- while not r in remainder and r != 0:
- remainder[r] = idx
- idx += 1
- tmp = r * 10
- tmp_q = tmp // d
- decimal.append(str(tmp_q))
- r = tmp % d
- # 当有小数的时候
- if decimal:
- if r == 0:
- res = str(q) + "." + "".join(decimal)
- else:
- # r != 0 说明是循环小数
- pos = remainder[r]
- decimal.insert(pos, "(")
- decimal.append(")")
- res = str(q) + "." + "".join(decimal)
- else:
- res = str(q)
- return sign + res
Advertisement
Add Comment
Please, Sign In to add comment