[LeetCode]166 分数到小数

题目描述

给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。

如果小数部分为循环小数,则将循环的部分括在括号内。

示例1

输入: numerator = 1, denominator = 2
输出: "0.5"

示例2

输入: numerator = 2, denominator = 1
输出: "2"

示例3

输入: numerator = 2, denominator = 3
输出: "0.(6)"

说明:

  • 版本字符串由以点 (.) 分隔的数字字符串组成。这个数字字符串可能有前导零。
  • 版本字符串不以点开始或结束,并且其中不会有两个连续的点。

思路

  • 模拟手算除法

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
n1=int(numerator)
n2=int(denominator)
minus=True if n1*n2<0 else False
n1=abs(n1)
n2=abs(n2)
res=[]
d={}
if n1==0:
return '0'
if n1>=n2 and n1%n2==0:
return str(n1//n2) if not minus else '-'+str(n1//n2)
temp=n1//n2
res.append(str(temp))
res.append('.')
n1=n1%n2
pos=2
while True:
d[n1]=pos
pos+=1
n1*=10
temp=n1//n2
res.append(str(temp))
n1=n1%n2
if n1 in d:
res.insert(d[n1],'(')
res.append(')')
res=''.join(res)
return res if not minus else '-'+res
if n1==0:
break
return ''.join(res) if not minus else '-'+''.join(res)