zoukankan      html  css  js  c++  java
  • [leetcode]166. Fraction to Recurring Decimal

    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.

    For example,

    • Given numerator = 1, denominator = 2, return "0.5".
    • Given numerator = 2, denominator = 1, return "2".
    • Given numerator = 2, denominator = 3, return "0.(6)".

    分数转变为小数,无限循环部分括起来

     1 class Solution(object):
     2     def fractionToDecimal(self, numerator, denominator):
     3         n,remainder = divmod(abs(numerator),abs(denominator))
     4         flag = '-' if numerator*denominator<0 else ''
     5         res = [flag+str(n),'.']
     6         s = []
     7         while remainder not in s:
     8             s.append(remainder)
     9             n,remainder = divmod(remainder*10,abs(denominator))
    10             res.append(str(n))
    11         i = s.index(remainder)
    12         res.insert(i+2,'(')
    13         res.append(')')
    14         return ''.join(res).replace('(0)','').rstrip('.')
    15         
  • 相关阅读:
    tomcat 添加用户名和密码
    linux系统下获取cpu、硬盘、内存使用率
    snmp 企业对应的mib编号
    String加密解密 2017.07.26
    Mongo日期
    linux sed 批量替换多个文件中的字符串
    Python和giL的关系
    vim
    乌班图
    Python
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6504208.html
Copyright © 2011-2022 走看看