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,
Credits:
Special thanks to @Shangrila for adding this problem and creating all test cases.
This is a straight forward coding problem but with a fair amount of details to get right.
\nIntuition
\nThe key insight here is to notice that once the remainder starts repeating, so does the divided result.
\n\n\n
\n
\nAlgorithm
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:
\nTest case | \nExplanation | \n
---|---|
\n\n | \nNumerator is zero. | \n
\n\n | \nDivisor is 0, should handle it by throwing an exception but here we ignore for simplicity sake. | \n
\n\n | \nAnswer is a whole integer, should not contain the fractional part. | \n
\n\n | \nAnswer is 0.5, no recurring decimal. | \n
\n or \n | \nOne of the numerator or denominator is negative, fraction is negative. | \n
\n\n | \nBoth numerator and denominator are negative, should result in positive fraction. | \n
\n\n | \nBeware of overflow if you cast to positive. | \n
\n