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.
- -2³¹ <= numerator, denominator <= 2³¹ - 1
- denominator != 0
- The answer string is shorter than 10⁴ characters
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.
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.
Approach
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).
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.
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.
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.
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.
Code in Python, C++ and Java
Common pitfalls
Taking the absolute value as a 32-bit int
int n = Math.abs(numerator);
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
if numerator < 0 or denominator < 0:
out.append("-")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
seen = set()
...
if r in seen:
# put "(" right after the pointseen = {}
...
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
out.append(str(numerator // denominator))
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.
Complexity
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.