Fraction to Recurring Decimal

Given two integers numerator and denominator, return the fraction numerator / denominator as a string. If the fractional part repeats, enclose the repeating part in parentheses. If several answers are possible, return any of them. The answer is guaranteed to be shorter than 10^4 characters for all inputs.

30:00

Fraction to Recurring Decimal
medium
Free written solution
Topics
Companies

Given two integers numerator and denominator, return the fraction numerator / denominator as a string. If the fractional part repeats, enclose the repeating part in parentheses. If several answers are possible, return any of them. The answer is guaranteed to be shorter than 10^4 characters for all inputs.

Example 1:
Input: {"numerator":1,"denominator":2}
Output: 0.5
Constraints:
  • −231≤numerator,denominator≤231−1-2^{31} \leq \text{numerator}, \text{denominator} \leq 2^{31} - 1

  • denominator≠0\text{denominator} \neq 0

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"numerator":1,"denominator":2}

Turn 1 / 2 into a decimal string. Long division writes one digit per remainder, and a repeated remainder means the digits repeat.

1
2

→

sign: ?
n = ?, d = ?

Answer being written

…

Long division, one digit per remainder

Nothing divided yet.

seen: remainder → digit position

empty

Variables
VariableValue
numerator1
denominator2
rem-
digits""
DepthFunction Call
Stack empty
0/8