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
Fraction to Recurring Decimal: 1 ÷ 3Input1 ÷ 3Long Division Process1.000... ÷ 3remainder: 110 ÷ 3 = 3remainder: 1 (repeat!)When remainder repeats, decimal repeatsOutput"0.(3)"Key Steps:1. Handle sign and integer part2. Track remainders with positions3. Insert parentheses on repetitionFinal Result: "0.(3)"
Understanding the Visualization
1
Input
numerator = 1, denominator = 3
2
Long Division
Perform division while tracking remainders
3
Output
"0.(3)" with parentheses around repeating part
Key Takeaway
🎯 Key Insight: When a remainder repeats during long division, the decimal pattern will repeat from that point forward
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.4K Views
Medium Frequency
~35 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen