https://leetcode.com/problems/fraction-to-recurring-decimal/description/

Tag: Math

Key Point:

Note how to identify repeating number

  1. Calculate integer part of the division
  2. Multiply the numerator by 10 repeatedly (append a zero) until it becomes larger than the denominator.
  3. Start recording the numerator at each step. If a numerator reappears, it marks the start of a repeating cycle in the decimal.

Solution:

def fractionToDecimal(self, numerator: int, denominator: int) -> str:
    if numerator == 0:
        return '0'

    if numerator < 0 and denominator < 0:
        return self.fractionToDecimal(abs(numerator), abs(denominator))
    if numerator < 0 or denominator < 0:
        return '-' + self.fractionToDecimal(abs(numerator), abs(denominator))

    int_part = numerator // denominator
    frac_part = numerator % denominator

    if frac_part == 0:
        return str(int_part)
    used = set()
    res = '.'
    while frac_part * 10 < denominator:
        res += '0'
        frac_part *= 10

    while frac_part != 0 and frac_part not in used:
        used.add(frac_part)
        frac_part *= 10
        res += str(frac_part // denominator)
        frac_part = frac_part % denominator

    if frac_part == 0:
        return str(int_part) + res
    repeat = frac_part * 10 // denominator
    idx = res.find(str(repeat))
    res = res[:idx] + '(' + res[idx:] + ')'
    return str(int_part) + res