Ctrl K

Fraction as a Decimal

Medium
You are given integers top and bottom. Write the fraction top / bottom as a decimal string. - If the fraction is a whole number, return just the integer part with no point: "7", "-3". - If the decimal expansion terminates, return all of it: "0.625". - If the fractional part repeats forever, wrap the repeating block in parentheses: "0.(3)", "2.41(6)". The parentheses open as early as possible and the block inside them is the shortest one. A negative result starts with a minus sign; zero has no sign.
Example 1
top=5, bottom=8 → '0.625'

5/8 = 0.625, which terminates, so no parentheses are needed.

Example 2
top=-29, bottom=12 → '-2.41(6)'

29/12 = 2.41666…: after the digits 4 and 1 the 6 repeats forever. The result is negative because the two inputs have opposite signs.

Example 3
top=3, bottom=37 → '0.(081)'

3/37 = 0.081081…, the three-digit block 081 repeats.

Constraints
  • -2³¹ ≤ top, bottom ≤ 2³¹ − 1
  • bottom ≠ 0
  • the answer is shorter than 10⁴ characters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNumber in Roman Numerals MediumDigits From Scrambled Words MediumPieces With Matching Ends MediumMessages Behind Key Presses MediumPieces With a Fixed Zero-to-One Ratio Medium
loading Python…
Input
top=5, bottom=8
Expected
'0.625'

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.