Fraction to Recurring Decimal - Problem
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, 1/3 = 0.(3) where 3 repeats infinitely.
If multiple answers are possible, return any of them. It is guaranteed that the length of the answer string is less than 10^4 for all the given inputs.
Note: If the fraction can be represented as a finite length string, you must return it without parentheses.
Input & Output
Example 1 — Simple Repeating Decimal
$
Input:
numerator = 1, denominator = 3
›
Output:
"0.(3)"
💡 Note:
1 ÷ 3 = 0.333... The digit 3 repeats infinitely, so we enclose it in parentheses: 0.(3)
Example 2 — Finite Decimal
$
Input:
numerator = 1, denominator = 2
›
Output:
"0.5"
💡 Note:
1 ÷ 2 = 0.5 exactly. Since it terminates, no parentheses are needed.
Example 3 — Negative with Repetition
$
Input:
numerator = -1, denominator = 6
›
Output:
"-0.1(6)"
💡 Note:
-1 ÷ 6 = -0.1666... The digit 6 repeats after the initial 1, so result is -0.1(6)
Constraints
- -231 ≤ numerator, denominator ≤ 231 - 1
- denominator ≠ 0
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code