動機
數論不好,當初居然是用算出來的商去看有沒有重複
Problem
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.
If multiple answers are possible, return any of them.
It is guaranteed that the length of the answer string is less than 104
for all the given inputs.
Example 1:
Input: numerator = 1, denominator = 2Output: 0.5
Example 2:
Input: numerator = 2, denominator = 1Output: 2
Example 3:
Input: numerator = 2, denominator = 3Output: 0.(6)
Example 4:
Input: numerator = 4, denominator = 333Output: 0.(012)
Example 5:
Input: numerator = 1, denominator = 5Output: 0.2
Constraints:
-231 <= numerator, denominator <= 231 - 1
denominator != 0
Sol
會出現重複就是因為要除的數字之前看過了,所以要看餘數有沒有出現過,不是看算出來的商有沒有出現過,有的是商是一樣的(“0.(0588235294117647)”)
再來就是要先把所有數字轉成正數,不然會出事
class Solution:
def f(self,n,d):
if n % d == 0:
self.ans += self.tbl
self.ans.append(str(n//d))
return
if str(n//d) == '0':
self.tbl.append(str(n//d))
self.f(n*10,d)
elif str(n//d) not in self.tbl:
print(str(n//d), (n%d)*10)
self.tbl.append(str(n//d))
self.f((n%d)*10,d)
else:
y = str(n//d)
for (i,x) in enumerate(self.tbl):
if x == y:
self.ans.append("(")
self.ans += [str(a) for a in self.tbl[i:]]
self.ans.append(")")
return
else:
self.ans.append(str(x))
def fractionToDecimal(self, n: int, d: int) -> str:
self.tbl = []
self.ans = []
self.ans.append(str(n//d))
if n > d:
n = n//d
if n%d != 0:
self.ans.append(".")
self.f((n%d)*10,d)
print(self.ans)
return ''.join(self.ans)