给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数 。

如果小数部分为循环小数,则将循环的部分括在括号内。

如果存在多个答案,只需返回 任意一个 。

对于所有给定的输入,保证 答案字符串的长度小于 104 。

示例 1:

输入:numerator = 1, denominator = 2
输出:"0.5"

示例 2:

输入:numerator = 2, denominator = 1
输出:"2"

示例 3:

输入:numerator = 2, denominator = 3
输出:"0.(6)"

示例 4:

输入:numerator = 4, denominator = 333
输出:"0.(012)"

示例 5:

输入:numerator = 1, denominator = 5
输出:"0.2"

提示:

  • -2^31 <= numerator, denominator <= 2^31 – 1
  • denominator != 0

Python 解答:

class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        adic = {}
        index = 0
        is_posivite = True
        if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
            is_posivite = False
        numerator, denominator = abs(numerator), abs(denominator)

        interger = numerator//denominator
        remainder = numerator % denominator
        pre = str(interger)
        if not is_posivite:
            pre = '-' + pre
        if remainder > 0:
            pre += '.'

        nex = []
        is_repeated = -1
        while remainder > 0:

            if remainder not in adic.keys():
                adic[remainder] = index
                index += 1
            else:
                is_repeated = adic[remainder]
                break

            numerator =  remainder*10
            interger, remainder = divmod(numerator, denominator)
            nex.append(str(interger))

            if len(nex)+len(pre) >= 10**4:
                break

        result = ''
        if is_repeated != -1:
            nex.insert(is_repeated, '(' )
            result = pre+''.join(nex)+')'
        else:
            result = pre+''.join(nex)
        return result
最后修改日期: 2021年8月20日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。