Fraction to Recurring Decimals

Problem: Fraction to Recurring Decimal

Based on dividing method, we can acknowledge that we can judge the repeating part by recurring nominator. For example, if we do 1 / 7:

Dividing

We can find that at last we got one, which means we will get repeating part. We can use a hash table to store corresponding nominator and position to define where the repeating part begins.

Code in Python:

from collections import defaultdict

class Solution(object):
    def fractionToDecimal(self, numerator, denominator):
        """
        :type numerator: int
        :type denominator: int
        :rtype: str
        """
        flag = numerator * denominator > 0
        n, d = abs(numerator), abs(denominator)
        if not n or not d:
            return '0'
        if not n % d:
            return str(n / d)  if flag else '-' + str(n / d)
        res = str(n / d) + '.'
        dict = defaultdict(int)
        pos = len(res)
        n %= d
        while n:
            if dict[n]:
                res = res[:dict[n]] + '(' + res[dict[n]:] + ')'
                break
            dict[n] = pos
            pos += 1
            res += str(n * 10 / d)
            n = n * 10 % d
        return res if flag else '-' + res

results matching ""

    No results matching ""