Fraction to Recurring Decimal - Problem
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
The challenge is that some fractions have repeating decimal parts. For example, 1/3 = 0.333... where 3 repeats infinitely. When this happens, you must enclose the repeating part in parentheses.
Examples:
1/2 = "0.5"(finite decimal)1/3 = "0.(3)"(repeating decimal)22/7 = "3.(142857)"(repeating cycle)
If the fraction can be represented as a finite decimal, return it without parentheses. The key insight is detecting when remainders start repeating during long division - that's when the decimal cycle begins!
Input & Output
example_1.py โ Simple Fraction
$
Input:
numerator = 1, denominator = 2
โบ
Output:
"0.5"
๐ก Note:
1/2 = 0.5, which is a finite decimal, so no parentheses are needed.
example_2.py โ Repeating Single Digit
$
Input:
numerator = 1, denominator = 3
โบ
Output:
"0.(3)"
๐ก Note:
1/3 = 0.333..., where 3 repeats indefinitely, so we enclose it in parentheses.
example_3.py โ Longer Repeating Cycle
$
Input:
numerator = 22, denominator = 7
โบ
Output:
"3.(142857)"
๐ก Note:
22/7 = 3.142857142857..., where 142857 repeats, forming a 6-digit cycle.
Constraints
- -231 โค numerator, denominator โค 231 - 1
- denominator โ 0
- The length of the answer string is less than 104
Visualization
Tap to expand
Understanding the Visualization
1
Setup Investigation
Handle the sign and calculate the integer part. Start tracking remainders with a hash map.
2
Follow the Trail
For each remainder in long division, check if we've seen it before. If not, record it with its position.
3
Catch the Repeat
The moment we see a repeated remainder, we've found our cycle! Insert parentheses around the repeating part.
4
Case Closed
Return the properly formatted decimal string with repeating parts in parentheses.
Key Takeaway
๐ฏ Key Insight: In long division, when the same remainder appears twice, the sequence of digits will repeat exactly from that point forward. Using a hash map to track remainder positions allows us to detect this cycle instantly and format the result correctly.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code