## [166\. 分數到小數](https://leetcode-cn.com/problems/fraction-to-recurring-decimal/)
> Medium
#### 思路
閱題,第一反應先計算出小數,看了眼實例,有限小數沒問題,無限小數這種方式做不到。
假如說把保留小數位數拉長呢?比如,1.66666667,6個數超過10個把他處理成循環主體,轉成1.(6)。但是不嚴謹且循環主體很長的話無法判斷,過!
又是數學題?google一下,獲得新思路
做一個長除法,就是我們小學在紙上計算的那種方式,當余數相同時,則產生循環,如圖:
* 符號問題記錄,最后再處理
* 分子分母為0的情況需處理
#### 代碼
python3
```
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
tag = 1 if numerator * denominator > 0 else -1
if numerator * denominator == 0:
return '0'
numerator = abs(numerator)
denominator = abs(denominator)
result = ''
# 整數部分
v = numerator // denominator
n = numerator % denominator # 余數
if n == 0:
return result + str(v) if tag > 0 else '-' + result + str(v)
result += str(v) + '.'
# 小數部分
n_cache = []
v_cache = []
while n not in n_cache and n != 0:
v = n * 10 // denominator
n_cache.append(n)
n = n * 10 - (v * denominator)
v_cache.append(v)
if n is 0:
result += ''.join(str(x) for x in v_cache)
else:
result += ''.join(str(x) for x in v_cache[:n_cache.index(n)]) \
+ '(' + ''.join(str(x) for x in v_cache[n_cache.index(n):]) + ')'
return result if tag > 0 else '-' + result
```
- 目錄
- excel-sheet-column-number
- divide-two-integers
- house-robber
- fraction-to-recurring-decimal
- profile
- kids-with-the-greatest-number-of-candies
- qiu-12n-lcof
- new-21-game
- product-of-array-except-self
- minimum-depth-of-binary-tree
- univalued-binary-tree
- shun-shi-zhen-da-yin-ju-zhen-lcof
- permutations
- satisfiability-of-equality-equations
- word-ladder-ii
- ba-shu-zi-fan-yi-cheng-zi-fu-chuan-lcof
- palindrome-number
- network-delay-time
- daily-temperatures
- longest-common-prefix
- sum-of-mutated-array-closest-to-target
- 周賽專題
- make-two-arrays-equal-by-reversing-sub-arrays
- check-if-a-string-contains-all-binary-codes-of-size-k
- course-schedule-iv
- cherry-pickup-ii
- maximum-product-of-two-elements-in-an-array
- maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
- reorder-routes-to-make-all-paths-lead-to-the-city-zero
- probability-of-a-two-boxes-having-the-same-number-of-distinct-balls
- shuffle-the-array
- the-k-strongest-values-in-an-array
- design-browser-history
- paint-house-iii
- final-prices-with-a-special-discount-in-a-shop