LeetcodeSep 03, 2025

Fraction to Recurring Decimal

Hazrat Ali

Leetcode

If the fractional part is repeating, enclose the repeating part in parentheses.

If multiple answers are possible, return any of them.

It is guaranteed that the length of the answer string is less than 104 for all the given inputs.

 

Example 1:

Input: numerator = 1, denominator = 2
Output: "0.5"

Example 2:

Input: numerator = 2, denominator = 1
Output: "2"

Example 3:

Input: numerator = 4, denominator = 333
Output: "0.(012)"

Solution
/**
 * @param {number} numerator
 * @param {number} denominator
 * @return {string}
 */
const fractionToDecimal = (numerator, denominator) => {

  if (denominator === 0) {
    return 'NaN';
  }

  if (numerator === 0) {
    return '0';
  }

  const result = [];

  if ((numerator < 0) ^ (denominator < 0)) {
    result.push('-');
  }

  const n = Math.abs(numerator);
  const d = Math.abs(denominator);

  result.push(Math.floor(n / d));

  if (n % d == 0) {
    return result.join('');
  }

  result.push('.');

  const map = new Map();

 
  for (let r = n % d; r > 0; r %= d) {
   
 
    if (map.has(r)) {
      result.splice(map.get(r), 0, '(');
      result.push(')');
      break;
    }

   
    map.set(r, result.length);

    r *= 10;
   
    result.push(Math.floor(r / d));
  }

  return result.join('');
};

const result = fractionToDecimal(1, 333);
console.log(result);



Comments

Fraction to Recurring Decimal