# 166. Fraction to Recurring Decimal
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
Example 1:
Input: numerator = 1, denominator = 2
Output: "0.5"
Example 2:
Input: numerator = 2, denominator = 1
Output: "2"
Example 3:
Input: numerator = 2, denominator = 3
Output: "0.(6)"
# Solution
Approach 1: Do one division, add the decimal if any, and then do the rest of divisions.
# Code (Python)
Approach 1:
# Code (C++)
Approach 1:
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
unordered_map<int,int> repeated;
ostringstream oss;
long n = numerator;
long d = denominator;
if (n < 0 && d > 0 || n > 0 && d < 0)
oss << '-';
// Do one division to add the decimal if any.
oss << std::abs(n / d);
n = (n % d) * 10;
if (n == 0)
return oss.str();
oss << '.';
// Do the rest after the decimal.
while (n != 0)
{
if (repeated.find(n) != repeated.end())
{
int pos = repeated[n];
string fraction = oss.str();
fraction = fraction.substr(0, pos) + '(' +
fraction.substr(pos, fraction.size() - pos) + ')';
return fraction;
}
repeated[n] = oss.str().size();
oss << std::abs(n / d);
n = (n % d) * 10;
}
return oss.str();
}
};