-
Handle sign: If numerator and denominator have different signs, the result should start with
-. Work with absolute values afterward. -
Integer part: Perform integer division (
numerator // denominator) to get the whole number part. -
Remainder handling: If the remainder is zero, just return the integer part as the answer.
-
Fractional part:
- Start simulating long division: multiply remainder by 10, divide by denominator, append quotient to result.
- Keep a dictionary mapping each remainder to the index in the result string where this remainder first appeared.
- If a remainder repeats, it means we’ve entered a repeating cycle. Insert parentheses around the repeating part and stop.
-
Return assembled string.
- Time:
$O(k)$ , where$k$ is the length of the decimal expansion before repetition - Space:
$O(k)$ to store remainders in the dictionary