291. Fraction to Decimal
A calculator app must show the exact value of a fraction as a decimal string instead of rounding it. Whenever the digits after the decimal point eventually repeat forever, the repeating block is written once, wrapped in parentheses, starting at the first digit that belongs to the cycle.
Given numerator and denominator, return the decimal expansion as a string. Use a leading - when the result is negative, print no decimal point for whole results, and print 0 for a zero numerator. For example 5/12 becomes 0.41(6) and -7/40 becomes -0.175. The inputs are not reduced, so the denominator may be negative and may share factors with the numerator. Beware of the extreme values near plus and minus 2^31. Aim for time linear in the length of the output.
Example 1
- Input:
- numerator = 5, denominator = 12
- Output:
- "0.41(6)"
- Explanation:
5/12 is 0.41666..., where only the 6 repeats, so the answer is 0.41(6).
Example 2
- Input:
- numerator = -7, denominator = 40
- Output:
- "-0.175"
- Explanation:
-7/40 terminates after three digits and is negative, giving -0.175.
Example 3
- Input:
- numerator = 13, denominator = -6
- Output:
- "-2.1(6)"
- Explanation:
13/-6 is -2.1666..., and the repeating 6 goes in parentheses.
Constraints
-231 ≤ numerator, denominator ≤ 231 - 1
denominator ≠ 0
The answer string is guaranteed to be shorter than 8,000 characters.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms
Expected complexity
- Time
- O(L)
- Space
- O(L)