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.


Summary

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

Hints

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

Solution


Approach #1 (Long Division) [Accepted]

Intuition

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


Algorithm

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.

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

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

Here are some good test cases:

Test case Explanation
Numerator is zero.
Divisor is 0, should handle it by throwing an exception but here we ignore for simplicity sake.
Answer is a whole integer, should not contain the fractional part.
Answer is 0.5, no recurring decimal.
or One of the numerator or denominator is negative, fraction is negative.
Both numerator and denominator are negative, should result in positive fraction.
Beware of overflow if you cast to positive.