MediumPro challengePythonJavaScriptTypeScript
Math — Fraction to Recurring Decimal
AlgorithmsMathHash MapStrings
solve(numerator, denominator) — return the fraction as a decimal string. If the
decimal part repeats, enclose the repeating digits in parentheses. The denominator is never 0
and the values fit in a signed 32-bit integer.
Do long division by hand. The remainder after each step fully determines the digits to come,
so a repeated remainder means a repeating decimal. Store, in a map, the position in the
output where each remainder first appeared; when one shows up again, insert ( at its stored
position and append ).
Handle the sign separately (a negative result needs exactly one of the two inputs negative,
and 0 is never "-0").
Examples
solve(1, 2) → "0.5"
solve(2, 1) → "2"
solve(4, 333) → "0.(012)"
solve(1, 6) → "0.1(6)"
solve(-50, 8) → "-6.25"Sample tests
Test #1Terminating decimal
Input: [1,2]
Output: "0.5"
Test #2Whole number
Input: [2,1]
Output: "2"
Test #3Whole fraction repeats
Input: [4,333]
Output: "0.(012)"