Prompt: Given two integers, a numerator and a denominator, return the fraction in the string. For any repeating fractional part, surround it with parentheses.
Example:
Input: numerator = 1, denominator = 2
Output: "0.5"
Input: numerator = 2, denominator = 1
Output: "2"
Input: numerator = 2, denominator = 3
Output: "0.(6)"
Input: numerator = 4, denominator = 333
Output: "0.(012)"
Input: numerator = 1, denominator = 5
Output: "0.2"
Solution: First, we simplify the problem by returning all numerator and denominator pairs that form a whole number.
Then, we can work on other pairs where there is a fractional part. We can get the part before the decimal by dividing the numerator and denominator and rounding down the result.
We can get the repeating part of the fraction by calculating the next digit of the part after the decimal. If there are no repeating parts, there should be a certain number of digits that can be calculated. If there are repeating parts, the digit should have been calculated earlier.
Knowing this, we can use a memory list where we can store all the digits that we have calculated. For the calculation of the next consecutive digit, we have to find the remainder and multiply it by 10 to move the remainder left 1 decimal place; we can equal this to the numerator. Finally, we can find the quotient by dividing the numerator with the denominator and rounding down the result. This rounded down quotient is the next consecutive digit after the decimal point.
The runtime for this solution is O(n) since it calculates the next consecutive digit of the fraction until it ends or it finds a repeating part.