【LeetCode 中等题】81-分数到小数

 题目描述:给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。如果小数部分为循环小数,则将循环的部分括在括号内。

示例 1:

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

示例 2:

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

示例 3:

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

解法1。每一位是除法也就是商的结果,而此题把循环转化为余数是否重复出现的结果,因为若是无限循环小数,那么除法取余后的结果重复就说明此处开始循环了,但商重复不代表开始循环了,如2.12123455…,但1234/9999=0.12341234…就是无限循环小数,且循环体长度大于1,此处注意,故用余数是否重复(出现在字典中)来表明循环是否开始

class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        if numerator == 0:
            return '0'
        elif denominator == 0:
            return ''
        else:
            isNegative = (numerator < 0) ^ (denominator < 0)
            numerator = abs(numerator)
            denominator = abs(denominator)
            res = ''
            res += '-' if isNegative else ''
            res += str(numerator//denominator)
            numerator %= denominator
            if numerator == 0:
                return res
            else:
                res +='.'
                dic = {}
                while numerator:
                    if numerator in dic:
                        start = dic[numerator]
                        end = len(res)
                        res = res[:start] + '(' + res[start:end] + ')'
                        return res
                    dic[numerator] = len(res)
                    res += str(numerator*10//denominator)
                    numerator = numerator*10%denominator
                return res

 

你可能感兴趣的:(LeetCode,中等,Medium)