https://leetcode.com/problems/fraction-to-recurring-decimal/
参考
http://yucoding.blogspot.hk/2015/03/leetcode-question-fraction-to-recurring.html
的计算方法。思路见code
class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
if numerator * denominator < 0:
pos = False
else:
pos = True
numerator = abs(numerator)
denominator = abs(denominator)
maxlen=1000#最多求到小数点后1000位
mod = []#reminder的集合
if numerator == 0 or denominator == 0:
return "0"
res = []#quotient的集合,也是结果的集合
l = -1
while len(mod) < maxlen:#一直除到小数位数超过给定的maxlen
res.append(numerator/denominator)
m = numerator % denominator
if m == 0:
break
if m in mod:
l = mod.index(m)#如果reminder在以前出现过,那么后面的结果就是在这个reminder对应的index开始不断的重复。重复res[l::]的结果,所以对这一部分加上括号就可以了
break
else:
mod.append(m)
numerator = m * 10
if len(res) == 1:#可以被整除,e.g. 6/3 = 2
s = str(res[0])
else:#结果是小数
s = str(res[0]) + "."
if l == -1:#结果是不循环小数
s = s + "".join([str(n) for n in res[1::]] )
else:#结果是循环小数
s = s+ "".join([str(n) for n in res[1:l+1]]) + "(" + "".join([str(n) for n in res[l+1::]]) + ")"
if pos:
return s
else:
return "-"+s
自己重写code
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
sign = 1
if numerator * denominator < 0:
sign = -1
numerator, denominator = abs(numerator), abs(denominator)
if numerator == 0 or denominator == 0: return '0'#这个注意加上
if numerator % denominator == 0 : return str(sign *numerator/denominator)
res = []
mod = []
res_index = -1
while len(mod) < 1000:
res1 = numerator / denominator
mod1 = numerator % denominator
if mod1 == 0:
res.append(str(res1))#这个要记得加上, 或者直接在计算res1的时候就res.append
break
elif mod1 in mod:
res_index = mod.index(mod1)
res.append(str(res1))#这个要记得加上, 或者直接在计算res1的时候就res.append
break
res.append(str(res1))
mod.append(mod1)
numerator = mod1 * 10
if res_index == -1:
if sign == -1:
return '-' + str(res[0]) + '.' +''.join(res[1:])
return str(res[0]) + '.' +''.join(res[1:])
else:
if sign == -1:
return '-' + str(res[0]) + '.' + ''.join(res[1:res_index + 1]) + '(' + ''.join(res[res_index + 1:]) + ')'
return str(res[0]) + '.' + ''.join(res[1:res_index + 1]) + '(' + ''.join(res[res_index + 1:]) + ')'