LeetCode #166 Medium

Fraction to Recurring Decimal

Fraction to Recurring Decimal is LeetCode 166 (Medium). Given two integers numerator and denominator, return the fraction as a decimal string. If the digits after the decimal point repeat forever, write the repeating part once, inside parentheses.

  • The numerator can be −2³¹, whose absolute value does not fit in a 32-bit int.
  • The answer is promised to be shorter than 10⁴ characters.
Constraints
  • -2³¹ <= numerator, denominator <= 2³¹ - 1
  • denominator != 0
  • The answer string is shorter than 10⁴ characters
mathhash-tablestrings
Open on LeetCode ↗
02

Intuition

Do the long division you learned at school and ask what decides each new digit. Only the current remainder: multiply it by 10, divide by the denominator, and you get the next digit and the next remainder. So if a remainder ever comes back, every digit after it comes back too, in the same order, forever.

  • Remember where each remainder appeared: store the position in the output where its digit is written. When it shows up again, the repeating part starts at that stored position.
  • A remainder of 0 ends it: the decimal is finite and needs no parentheses.

There are only denominator − 1 non-zero remainders, so one of the two must happen.

How to spot this pattern

A process whose next state depends only on the current state must repeat once it runs out of new states. Store each state with the step where it first appeared; the first repeat tells you exactly where the cycle starts.

03

Approach

Try it first

Before reading on, divide 1 by 6 by hand and write each remainder next to the digit it produces. Find where the first repeated remainder appeared, and check that the answer is 0.1(6), not 0.(16).

1

Handle zero and the sign first

If numerator is 0, return "0" before anything else, so 0 divided by a negative number never gets a minus sign. Otherwise the result is negative when exactly one of the numbers is negative: write -, then continue with absolute values so the division never mixes signs.

2

Write the whole-number part

Append n // d and keep the remainder r = n % d. If r is 0 the division is exact, so return straight away with no decimal point.

3

Divide one digit at a time, recording each remainder

Append ., then loop while r is not 0. Store seen[r] as the current length of the output, multiply r by 10, append r // d as the next digit and keep r % d. The stored length is exactly where the digit from that remainder is written.

4

Close the brackets on a repeat

At the top of each pass, check whether r is already in seen. If it is, insert ( at position seen[r], append ) and stop: the digits from that position to the end are the part that repeats.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def fractionToDecimal(self, numerator: int, denominator: int) -> str:
▶3 if numerator == 0:
▶4 return "0"
▶5 out = []
▶6 if (numerator < 0) != (denominator < 0):
▶7 out.append("-")
▶8 n, d = abs(numerator), abs(denominator)
▶9 out.append(str(n // d))
▶10 r = n % d
▶11 if r == 0:
▶12 return "".join(out)
▶13 out.append(".")
▶14 seen = {}
▶15 while r:
▶16 if r in seen:
▶17 out.insert(seen[r], "(")
▶18 out.append(")")
▶19 break
▶20 seen[r] = len(out)
▶21 r *= 10
▶22 out.append(str(r // d))
▶23 r %= d
▶24 return "".join(out)
answer so farlong divisionremainders seen → positionnot 0, and the signs match → no minus sign
numerator4
denominator333
sign+
The numerator is not 0, and the two numbers have the same sign, so the answer is positive. The division works on 4 and 333.
answer so far00whole-number part4numerator÷333denominator=0whole part4remainder leftremainders seen → position4 ÷ 333 = 0 with 4 left → write 0
whole part0
remainder4
333 goes into 4 0 times, leaving 4. The whole part 0 is written before any decimal point.
answer so far00.1long divisionremainders seen → position4 left over → write the decimal point
remainder4
A remainder of 4 means the fraction has digits after the point. From here on, each remainder produces exactly one digit.
answer so far00.102long division40remainder × 10÷333denominator=0next digit40remainder leftremainders seen → position4wrote at 2new remainder 4 → position 2: 40 ÷ 333 = 0, 40 left
remainder4
digit0
next remainder40
Remainder 4 has not appeared before, so remember that it writes position 2. Then 4 × 10 = 40, and 333 goes into 40 0 times with 40 left.
answer so far00.10213long division400remainder × 10÷333denominator=1next digit67remainder leftremainders seen → position4wrote at 240wrote at 3new remainder 40 → position 3: 400 ÷ 333 = 1, 67 left
remainder40
digit1
next remainder67
Remainder 40 has not appeared before, so remember that it writes position 3. Then 40 × 10 = 400, and 333 goes into 400 1 time with 67 left.
answer so far00.1021324long division670remainder × 10÷333denominator=2next digit4remainder leftremainders seen → position4wrote at 240wrote at 367wrote at 4new remainder 67 → position 4: 670 ÷ 333 = 2, 4 left
remainder67
digit2
next remainder4
Remainder 67 has not appeared before, so remember that it writes position 4. Then 67 × 10 = 670, and 333 goes into 670 2 times with 4 left.
answer so far00.1(2031425)6long divisionremainders seen → position4wrote at 240wrote at 367wrote at 4remainder 4 again → the repeat starts at position 2
remainder4
first seen at2
Remainder 4 already appeared, and the digit it produced went to position 2. The same remainder will produce the same digits again, forever, so ( goes in at position 2 and ) at the end.
answer so far00.1(2031425)6long divisionremainders seen → position4wrote at 240wrote at 367wrote at 4done: the digits in brackets repeat forever
answer"0.(012)"
The digits inside the brackets repeat forever; the ones before them appear once.
05

Common pitfalls

Taking the absolute value as a 32-bit int

✗ Wrong
int n = Math.abs(numerator);
✓ Right
long n = Math.abs((long) numerator);

The absolute value of −2³¹ is 2³¹, one more than the largest int. In Java Math.abs(-2147483648) stays negative, and in C++ it is undefined behaviour, so numerator = -2147483648, denominator = -1 cannot produce "2147483648". Convert to 64 bits before abs.

Deciding the sign with or

✗ Wrong
if numerator < 0 or denominator < 0:
    out.append("-")
✓ Right
if (numerator < 0) != (denominator < 0):
    out.append("-")

Two negatives make a positive. With or, −1 / −2 returns "-0.5" instead of "0.5". The minus sign belongs only when exactly one of the numbers is negative.

Remembering only that a remainder was seen

✗ Wrong
seen = set()
...
if r in seen:
    # put "(" right after the point
✓ Right
seen = {}
...
seen[r] = len(out)
if r in seen:
    out.insert(seen[r], "(")

A set tells you the digits repeat, but not where the repeat begins. For 1/6 the remainders are 1, then 4, then 4 again, so only the 6 repeats: the answer is 0.1(6). Bracketing everything after the point gives 0.(16).

Dividing before removing the signs in Python

✗ Wrong
out.append(str(numerator // denominator))
✓ Right
n, d = abs(numerator), abs(denominator)
out.append(str(n // d))

Python's // rounds down, not toward zero. −50 / 8 is −6.25, but -50 // 8 is −7 and -50 % 8 is 6, so the code builds "-7.75". Working on absolute values and adding the sign separately avoids it.

06

Complexity

Time
O(d)
Space
O(d)
Each pass writes one digit and one new remainder. There are at most |denominator| − 1 different non-zero remainders, so the loop stops (by repeating or reaching 0) within that many passes, and the map holds one entry per pass. The problem also caps the answer below 10⁴ characters.
07

Fraction to Recurring Decimal FAQ

How long can the repeating part be?

Up to |denominator| − 1 digits, when every non-zero remainder appears before the first repeat. 1/7 is the classic case: the remainders run through 1, 3, 2, 6, 4, 5 and the answer is 0.(142857), six digits for a denominator of 7.

Which fractions give a finite decimal?

Reduce the fraction first. If the denominator then has no prime factors other than 2 and 5, the remainder eventually hits 0 and the decimal ends, as with 3/8 = 0.375. Any other prime factor, such as the 3 in 1/6, makes it recur.

How do you turn a recurring decimal back into a fraction?

Multiply to shift one full repeat past the point and subtract. For x = 0.(012), 1000x = 12.(012), so 999x = 12 and x = 12/999 = 4/333. With digits before the repeat, as in 0.1(6), first multiply by 10 to move the 1 in front of the point.