Skip to content

166. Fraction To Recurring Decimal

Hash Table Math String

Problem - Fraction To Recurring Decimal

Medium

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.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

 

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

 

Constraints:

  • -231 <= numerator, denominator <= 231 - 1
  • denominator != 0

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
    def fractionToDecimal(self, numerator: int, denominator: int) -> str:
        if numerator == 0:
            return "0"

        neg = (numerator < 0) != (denominator < 0)
        result = []
        if neg:
            result.append("-")

        num, denom = abs(numerator), abs(denominator)
        result.append(str(num // denom))
        num %= denom

        if num == 0:
            return "".join(result)
        result.append(".")

        hash_map = {}
        while num:
            hash_map[num] = len(result)
            num *= 10
            result.append(str(num // denom))
            num %= denom
            if num in hash_map:
                result.insert(hash_map[num], "(")
                result.append(")")
                break

        return "".join(result)

Submission Stats:

  • Runtime: 0 ms (100.00%)
  • Memory: 18.2 MB (20.31%)