Skip to content

166 Fraction to Recurring Decimal

166. Fraction to Recurring Decimal

题目: https://leetcode.com/problems/fraction-to-recurring-decima/

难度:

Medium

class Solution:
    # @return a string
    def fractionToDecimal(self, n, d):
        res = ''
        if n == 0: # zero numerator
            return str(n)
        if (n < 0) ^ (d < 0): # determine the sign
            res += '-'
        n = abs(n) # remove sign of operands
        d = abs(d) 
        res += str(n / d) # append integral part
        if (n % d == 0): # in case no fractional part
            return res
        res += '.'
        r = n % d
        m = {}
        while r: # simulate the division process
            if r in m: # meet a known remainder
                res = res[:m[r]] + '(' + res[m[r]:] + ')' # so we reach the end of the repeating part
                break
            m[r] = len(res) # if the remainder is first seen, remember the current position for it
            r *= 10
            res += str(r / d) # append the quotient digit
            r %= d
        return res


回到顶部