## 166. Fraction to Recurring Decimal

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.

For example,

• Given numerator = 1, denominator = 2, return "0.5".
• Given numerator = 2, denominator = 1, return "2".
• Given numerator = 2, denominator = 3, return "0.(6)".

Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.

b'
\n
\n\n
\n

## Summary

\n

This is a straight forward coding problem but with a fair amount of details to get right.

\n

## Hints

\n
\n
1. No scary math, just apply elementary math knowledge. Still remember how to perform a long division?
2. \n
3. Try a long division on , the repeating part is obvious. Now try . Do you see a pattern?
4. \n
5. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
6. \n
\n

## Solution

\n
\n

#### Approach #1 (Long Division) [Accepted]

\n

Intuition

\n

The key insight here is to notice that once the remainder starts repeating, so does the divided result.

\n

\n\n

\n

\nAlgorithm

\n

You will need a hash table that maps from the remainder to its position of the fractional part. Once you found a repeating remainder, you may enclose the reoccurring fractional part with parentheses by consulting the position from the table.

\n

The remainder could be zero while doing the division. That means there is no repeating fractional part and you should stop right away.

\n

Just like the question Divide Two Integers, be wary of edge cases such as negative fractions and nasty extreme case such as .

\n

Here are some good test cases:

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Test caseExplanation
\n\nNumerator is zero.
\n\nDivisor is 0, should handle it by throwing an exception but here we ignore for simplicity sake.
\n\nAnswer is a whole integer, should not contain the fractional part.
\n\nAnswer is 0.5, no recurring decimal.
\n or \nOne of the numerator or denominator is negative, fraction is negative.
\n\nBoth numerator and denominator are negative, should result in positive fraction.
\n\nBeware of overflow if you cast to positive.
\n

\n

\n
'