Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created September 24, 2025 18:30
Show Gist options
  • Select an option

  • Save tatsuyax25/fc54d1aee37ea7168993e53df69617d9 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/fc54d1aee37ea7168993e53df69617d9 to your computer and use it in GitHub Desktop.
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. If multiple answers are possible, return any of them.
/**
* @param {number} numerator
* @param {number} denominator
* @return {string}
*/
var fractionToDecimal = function(numerator, denominator) {
if (numerator === 0) return "0";
let result = "";
// Handle negative signs
if ((numerator < 0) ^ (denominator < 0)) result += "-";
// Convert to absolute values to simplify
let num = Math.abs(numerator);
let den = Math.abs(denominator);
// Append the integer part
result += Math.floor(num / den);
let remainder = num % den;
if (remainder === 0) return result;
result += ".";
// Map to store previously seen remainders and their positions
let map = new Map();
while (remainder !== 0) {
if (map.has(remainder)) {
// Insert parentheses around the repeating part
let index = map.get(remainder);
result = result.slice(0, index) + "(" + result.slice(index) + ")";
break;
}
map.set(remainder, result.length);
remainder *= 10;
result += Math.floor(remainder / den);
remainder %= den;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment