題目:
分數到小數:給定兩個整數,分別表示分數的分子 numerator 和分母 denominator,以字符串形式返回小數。 如果小數部分為循環小數,則將循環的部分括在括號內。
思路:
一開始想到用哈希表來存儲小數點后的部分,就是沒有想出一個很好的表達,一直也不對,看來一個大神的解答,寫的很好啊,學習了,自己按照他的思想寫了一下,此外,這道題涉及到的細節問題有很多,得注意。
程序:
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return '0'
if denominator == 0:
return 'Nan'
if numerator * denominator < 0:
sign = '-'
if numerator * denominator > 0:
sign = ''
numerator = abs(numerator)
denominator = abs(denominator)
a, b = divmod(numerator, denominator)
if b == 0:
return sign + str(a)
result = sign + str(a) + '.'
myHashMap = {}
index = len(result)
while b != 0:
if b not in myHashMap:
myHashMap[b] = index
else:
index = myHashMap[b]
result = result[: index] + '('+ result[index :] +')'
return result
a, b = divmod(b * 10, denominator)
result += str(a)
index += 1
return result