Fraction to Recurring Decimal

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2021-04-30

Problem Statement

Design a class-based system that converts a given fraction (numerator/denominator) into its decimal representation, where any recurring decimal part is enclosed within parentheses.


For example:


•1 / 2 → "0.5"
•2 / 3 → "0.(6)"
•4 / 333 → "0.(012)"
•-50 / 8 → "-6.25"


🎯 Objective


You need to build a system that:


•Accepts two integers: numerator and denominator.
•Returns a string representing the decimal expansion.
•Correctly handles recurring decimal patterns, signs, and edge cases like zeros or negative numbers.


✅ Functional Requirements


Input:

•Two integers: numerator and denominator.

Output:

•A string representing the fraction as a decimal.
•If the decimal part repeats, enclose the recurring part in parentheses.

Edge Cases:

•Numerator = 0 → output "0".
•Denominator = 0 → throw/handle DivideByZeroException.
•Negative inputs → output string should contain '-' if result is negative.
•Large numerators or denominators → should not cause overflow.

Optional Functionalities:

•Configurable output precision (limit recurring detection up to N digits).
•Support for rational number simplification.
•Support for mixed fractions (e.g., "1 1/2" format).


⚙️ Non-Functional Requirements


Aspect with Description


Time Complexity

O(n) where n = number of digits before repeat cycle


Space Complexity

O(n) to store remainder mappings


Accuracy

100% accurate recurring detection


Readability

Code should be clean, modular, and maintainable


Extensibility

Easy to extend for arbitrary precision decimals


🧱 Key Classes and Responsibilities


1. Fraction

Encapsulates numerator and denominator details and provides basic validation.

1 2class Fraction { 3 private long numerator; 4 private long denominator; 5 6 public Fraction(long numerator, long denominator); 7 public boolean isNegative(); 8 public long getAbsoluteNumerator(); 9 public long getAbsoluteDenominator(); 10}


2. DecimalConverter

Handles conversion logic, including integer part, decimal part, and recurring sequence detection.

1 2class DecimalConverter { 3 public String convert(Fraction fraction); 4}


Responsibilities:


•Compute integer part: numerator / denominator
•Use remainder tracking (HashMap) to detect repetition
•Format recurring sequence with parentheses


3. FractionToDecimalService

High-level interface or facade that clients can use.

1 2class FractionToDecimalService { 3 private DecimalConverter converter; 4 5 public String convertToDecimal(long numerator, long denominator); 6}


4. RemainderTracker (optional utility)

Keeps track of remainders to identify recurring cycles.

1 2class RemainderTracker { 3 private Map<Long, Integer> remainderPositionMap; 4 5 public void addRemainder(long remainder, int position); 6 public boolean hasSeen(long remainder); 7 public int getPosition(long remainder); 8}


🔄 Example Flow


Input:

1 2numerator = 22, denominator = 7


Process:

1 222 ÷ 7 = 3.142857142857... 3Recurring part: "142857"


Output:

1 2"3.(142857)"


🧠 Algorithm Steps


1.Determine the sign of the result.
2.Divide numerator by denominator → integer part.
3.Compute remainder → start fractional part.
4.Use a Map<remainder, position> to detect cycles.
5.For each new remainder:
•Multiply by 10, divide by denominator → next digit.
•If the remainder repeats, wrap digits from that index with parentheses.
6.Return formatted string.


🧾 Example Inputs/Outputs


NumeratorDenominatorOutput


| Numerator | Denominator | Output |


| 1 | 2 | `"0.5"` |

| 1 | 3 | `"0.(3)"` |

| 4 | 333 | `"0.(012)"` |

| -50 | 8 | `"-6.25"` |

| 7 | -12 | `"-0.58(3)"` |

| 0 | 7 | `"0"` |



🧩 Design Highlights


•Encapsulation: Core conversion logic hidden behind DecimalConverter.
•Reusability: Fraction class reusable for arithmetic or future features.
•Extensibility: New output formats (e.g., mixed fraction, percentage) can be added easily.
•Error Handling: Proper handling of zero denominator, negative inputs.


🚀 Bonus Extensions


•Add precision limit for very large repeating sequences.
•Support BigDecimal for arbitrary-length fractional parts.
•Allow output in scientific notation (e.g., "1.23e-4").


Solution

Comments