Fraction to Recurring Decimal

Long-divide numerator by denominator and wrap the repeating cycle in parentheses.

Medium
Time O(D) Space O(D)
LeetCode
5 min read
hash-map math strings

Problem#

Given numerator and denominator integers, return the fraction as a string. If the fractional part repeats, enclose the repeating block in parentheses.

Examples#

  • 1/2"0.5".
  • 2/1"2".
  • 4/333"0.(012)".
  • 1/6"0.1(6)".

Constraints#

  • -2^31 <= num, den <= 2^31 - 1, den != 0.

Hints#

Hint
During long division, record each remainder and the position where it first appeared. A repeat means a cycle starts there.

Approach#

Handle sign and integer part. For the fractional part, simulate long division: at each step, multiply remainder by 10, append rem / den as a digit, set rem = rem % den. A repeated remainder means the cycle restarts there — insert ( at the recorded position and append ).

Solution#

Fraction to Recurring Decimal
class Solution {
public:
string fractionToDecimal(int numerator, int denominator) {
if (numerator == 0) return "0";
string ans;
long long num = numerator, den = denominator;
if ((num < 0) ^ (den < 0)) ans.push_back('-');
num = abs(num); den = abs(den);
ans += to_string(num / den);
long long rem = num % den;
if (rem == 0) return ans;
ans.push_back('.');
unordered_map<long long, int> seen;
while (rem != 0) {
auto it = seen.find(rem);
if (it != seen.end()) {
ans.insert(it->second, "(");
ans.push_back(')');
break;
}
seen[rem] = ans.size();
rem *= 10;
ans += to_string(rem / den);
rem %= den;
}
return ans;
}
};

Editorial#

Long division produces a repeating remainder iff the fraction is non-terminating, and the cycle starts at exactly the first re-seen remainder. The hash map remembers each remainder’s output position, so the moment we revisit one we know where to insert (. Using long long avoids overflow on INT_MIN / -1 and on the abs of INT_MIN.

Complexity#

  • Time: O(D) — at most den distinct remainders before a cycle.
  • Space: O(D).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.