166. 分数到小数

Medium

思路

阅题,第一反应先计算出小数,看了眼实例,有限小数没问题,无限小数这种方式做不到。
假如说把保留小数位数拉长呢?比如,1.66666667,6个数超过10个把他处理成循环主体,转成1.(6)。但是不严谨且循环主体很长的话无法判断,过!
又是数学题?google一下,获得新思路
做一个长除法,就是我们小学在纸上计算的那种方式,当余数相同时,则产生循环,如图:fraction-to-recurring-decimal - 图1

  • 符号问题记录,最后再处理
  • 分子分母为0的情况需处理

代码

python3

  1. class Solution:
  2. def fractionToDecimal(self, numerator: int, denominator: int) -> str:
  3. tag = 1 if numerator * denominator > 0 else -1
  4. if numerator * denominator == 0:
  5. return '0'
  6. numerator = abs(numerator)
  7. denominator = abs(denominator)
  8. result = ''
  9. # 整数部分
  10. v = numerator // denominator
  11. n = numerator % denominator # 余数
  12. if n == 0:
  13. return result + str(v) if tag > 0 else '-' + result + str(v)
  14. result += str(v) + '.'
  15. # 小数部分
  16. n_cache = []
  17. v_cache = []
  18. while n not in n_cache and n != 0:
  19. v = n * 10 // denominator
  20. n_cache.append(n)
  21. n = n * 10 - (v * denominator)
  22. v_cache.append(v)
  23. if n is 0:
  24. result += ''.join(str(x) for x in v_cache)
  25. else:
  26. result += ''.join(str(x) for x in v_cache[:n_cache.index(n)]) \
  27. + '(' + ''.join(str(x) for x in v_cache[n_cache.index(n):]) + ')'
  28. return result if tag > 0 else '-' + result