Tutorialspoint
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)
NumberDeloitteeBay
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Handle the special case where numerator is 0, return "0"
 Step 2: Determine the sign of the result based on numerator and denominator signs
 Step 3: Convert both numerator and denominator to positive values for easier calculation
 Step 4: Calculate and append the integer part of the division to the result string
 Step 5: If there's no remainder after integer division, return the result
 Step 6: Add decimal point and use a hash map to track remainders and their positions
 Step 7: For each remainder, multiply by 10, divide by denominator, and check for recurring pattern

Submitted Code :