|
| 1 | +/** |
| 2 | + * 166. Fraction to Recurring Decimal |
| 3 | + * https://leetcode.com/problems/fraction-to-recurring-decimal/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given two integers representing the numerator and denominator of a fraction, return |
| 7 | + * the fraction in string format. |
| 8 | + * |
| 9 | + * If the fractional part is repeating, enclose the repeating part in parentheses. |
| 10 | + * |
| 11 | + * If multiple answers are possible, return any of them. |
| 12 | + * |
| 13 | + * It is guaranteed that the length of the answer string is less than 104 for all the |
| 14 | + * given inputs. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number} numerator |
| 19 | + * @param {number} denominator |
| 20 | + * @return {string} |
| 21 | + */ |
| 22 | +var fractionToDecimal = function(numerator, denominator) { |
| 23 | + if (numerator === 0) return '0'; |
| 24 | + |
| 25 | + const map = new Map(); |
| 26 | + let result = ''; |
| 27 | + |
| 28 | + if (Math.sign(numerator) !== Math.sign(denominator)) { |
| 29 | + result += '-'; |
| 30 | + } |
| 31 | + |
| 32 | + numerator = Math.abs(numerator); |
| 33 | + denominator = Math.abs(denominator); |
| 34 | + result += Math.floor(numerator / denominator); |
| 35 | + |
| 36 | + let remainder = numerator % denominator; |
| 37 | + while (remainder) { |
| 38 | + result = result.indexOf('.') === -1 ? `${result}.` : result; |
| 39 | + if (map.has(remainder)) { |
| 40 | + const index = map.get(remainder); |
| 41 | + result = `${result.slice(0, index)}(${result.slice(index)})`; |
| 42 | + break; |
| 43 | + } |
| 44 | + map.set(remainder, result.length); |
| 45 | + remainder *= 10; |
| 46 | + result += Math.floor(remainder / denominator); |
| 47 | + remainder %= denominator; |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | +}; |
0 commit comments