Show problems as
Classic problem #166MediumHash TableMathString

Fraction to Recurring Decimal

Real-world version: Ratio Printed as a Decimal
Tracked in this browser only
Read Fraction to Recurring Decimal on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A reporting tool has to print the ratio numerator / denominator in ordinary decimal notation and return it as a string. Follow this format exactly.

  • A leading - appears when and only when the true value is below zero. A value of zero is printed as 0, never as -0.
  • When the ratio comes out whole, print only the digits of that whole number and no decimal point. So a ratio worth two is printed as 2.
  • Otherwise print the whole part, then a ., then the digits after the point. A value between -1 and 1 has a whole part of 0, as in 0.75 or -0.75.
  • The digits after the point may run on forever, in which case they finish with a block of digits that repeats over and over. Enclose that block in ( and ) and stop there. The ( goes at the earliest digit from which the repeat runs unbroken to the end, and the block inside the brackets must be as short as possible. So one ninth is 0.(1), one sixth is 0.1(6), and one forty-fourth is 0.02(27).
  • When the digits after the point stop, print them and nothing more, as in 0.875.

Return that string.

Examples

Example 1

Input
numerator = 7, denominator = 8
Output
"0.875"

Seven eighths is 0.875 and the digits after the point stop, so no brackets appear.

Example 2

Input
numerator = 5, denominator = 44
Output
"0.11(36)"

The digits after the point run 1, 1, 3, 6, 3, 6, 3, 6 and onward. The repeat is the pair 36 and the earliest place it starts running unbroken is the third digit, so the first two digits sit outside the brackets.

Example 3

Input
numerator = -9, denominator = 4
Output
"-2.25"

The value is below zero, so the string opens with a minus sign, and nine quarters is 2.25.

Example 4

Input
numerator = 8, denominator = 4
Output
"2"

Eight divided by four comes out whole, so only the digits of the whole number are printed and there is no decimal point.

Constraints

  • -2^31 <= numerator, denominator <= 2^31 - 1
  • denominator != 0
  • The inputs are chosen so that the returned string holds at most 10^4 characters.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def fraction_to_decimal(numerator: int, denominator: int) -> str:
Java
public String fractionToDecimal(int numerator, int denominator)