FastPrepFraction to Recurring Decimal

Fraction to Recurring Decimal

Airbnb logoAirbnb● MediumFULLTIMEOA
Learn

Problem statement

Given two integers numerator and denominator, return their exact decimal representation as a string.

  • If the fractional part terminates, return it normally.
  • If part of the fractional digits repeats forever, enclose the repeating part in parentheses.
  • Include a leading minus sign exactly when the result is negative.

The result must not contain unnecessary leading zeros or a decimal point when the value is an integer.

Function

fractionToDecimal(numerator: int, denominator: int) → String

Examples

Example 1

numerator = 1denominator = 2return = "0.5"

The remainder becomes zero after one decimal digit.

Example 2

numerator = 2denominator = 3return = "0.(6)"

Remainder 2 repeats, so digit 6 is enclosed in parentheses.

Example 3

numerator = -50denominator = 8return = "-6.25"

The signs differ and the fractional part terminates.

Constraints

  • -2^31 <= numerator <= 2^31 - 1.
  • -2^31 <= denominator <= 2^31 - 1.
  • denominator != 0.

More Airbnb problems

See Airbnb hiring insights
public String fractionToDecimal(int numerator, int denominator) {
  // Write your code here.
}
numerator1
denominator2
expected"0.5"
Checking account…