
Problem
Solution
Submissions
Fraction to Recurring Decimal
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a C program to convert a fraction (numerator/denominator) to its decimal representation. If the decimal part is recurring, enclose the recurring part in parentheses. The program should handle both positive and negative fractions and return the result as a string.
Example 1
- Input: numerator = 1, denominator = 2
- Output: "0.5"
- Explanation: 1/2 = 0.5. There is no recurring decimal part. Therefore, the result is "0.5".
Example 2
- Input: numerator = 2, denominator = 3
- Output: "0.(6)"
- Explanation: 2/3 = 0.666... The digit 6 repeats indefinitely. Therefore, the result is "0.(6)".
Constraints
- -2^31 ≤ numerator, denominator ≤ 2^31 - 1
- denominator != 0
- The result string length should not exceed 10^4 characters
- Time Complexity: O(denominator)
- Space Complexity: O(denominator)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Handle the sign of the result first (negative if numerator and denominator have different signs)
- Convert both numerator and denominator to positive values to simplify calculation
- Calculate the integer part by dividing numerator by denominator
- Use a hash map to track remainders and their positions to detect recurring patterns
- For each remainder, multiply by 10 and divide by denominator to get the next decimal digit
- If a remainder repeats, you've found the start of the recurring cycle