Skip to content
BytePatterns

Fraction as a Repeating Decimal

MediumMath & Number Theory#long-division#hash-map~30m

Problem

Given an integer numerator and a non-zero integer denominator, return the value of the fraction as a decimal string. If the digits after the point repeat forever, wrap the repeating block in parentheses. Either number may be negative, and the result carries a minus sign only when the value itself is negative.

Examples

Input:  num = 1, den = 6
Output: "0.1(6)"
Why:    1/6 = 0.1666..., the 6 repeats after one digit that does not
Input:  num = 22, den = 7
Output: "3.(142857)"
Input:  num = -50, den = 8
Output: "-6.25"
Why:    edge case, a negative value whose digits stop

Hints

0 / 3

Stuck on the idea rather than the code? Modular Arithmetic covers it.