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.
For example,
Given numerator = 1, denominator = 2, return “0.5”.
Given numerator = 2, denominator = 1, return “2”.
Given numerator = 2, denominator = 3, return “0.(6)”.
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路
几个注意点:
正负号问题,numerator=0问题
解法是使用两个字典,一个字典key=余数,value=下一个相除结果
另外一个字典key=余数,value=当前的位置,同时计算时用一个列表将结果一一加入
余数==0或者余数已经在字典1中出现,则当前位置以前的序列是括号外面的字符串,当前位置以后是括号里面的字符串
注意一些细节,比如temp要重新赋值等等~~
class Solution(object):
def fractionToDecimal(self,numerator,denominator):
if (numerator>=0 and denominator>0) or (numerator<=0 and denominator<0):
flag=1
else:
flag=0
numerator=abs(numerator)
denominator=abs(denominator)
intenger=numerator/denominator
remainder=numerator%denominator
if remainder==0:
if not flag:
ss='-'+str(intenger)
else:
ss=str(intenger)
return ss
doc={}
ans=[]
id1={}
i=0
while remainder!=0 and remainder not in doc:
temp=remainder*10/denominator
doc.setdefault(remainder,temp)
id1.setdefault(remainder,i)
i=i+1
ans.append(str(temp))
remainder=remainder*10%denominator
temp=remainder*10/denominator
if remainder:
t1="".join([ans[i] for i in range(id1[remainder])])
t2="".join([ans[i] for i in range(id1[remainder],len(ans))])
if t1:
s=str(intenger)+'.'+t1+'('+t2+')'
else:
s=str(intenger)+'.('+t2+')'
else:
ss="".join([ans[i] for i in range(len(ans))])
s=str(intenger)+'.'+ss
if not flag:
s='-'+s
return s