Fraction to Recurring Decimal
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:
🎯 Objective
You need to build a system that:
✅ Functional Requirements
Input:
Output:
Edge Cases:
Optional Functionalities:
⚙️ 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:
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 = 7Process:
1
222 ÷ 7 = 3.142857142857...
3Recurring part: "142857"Output:
1
2"3.(142857)"🧠 Algorithm Steps
🧾 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
🚀 Bonus Extensions