This website contains ALL LeetCode **Premium** problems for
**FREE!!**.

All leaked interview problems are collected from Internet.

All leaked interview problems are collected from Internet.

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## Summary

\n## Hints

\n## Solution

\n

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

\n

\n

'
\n\n

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

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

\n

**Intuition**

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

\n\n\n

\n

\n**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.

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

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

\nHere 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\nTest case | Explanation |
---|---|

\n\n | Numerator is zero. |

\n\n | Divisor is 0, should handle it by throwing an exception but here we ignore for simplicity sake. |

\n\n | Answer is a whole integer, should not contain the fractional part. |

\n\n | Answer is 0.5, no recurring decimal. |

\n or \n | One of the numerator or denominator is negative, fraction is negative. |

\n\n | Both numerator and denominator are negative, should result in positive fraction. |

\n\n | Beware of overflow if you cast to positive. |

\n