
Sponsored
Sponsored
This method utilizes long division to compute the fraction part. We keep track of the remainder at each step using a hash map (or dictionary), which maps the remainder to its corresponding position in the decimal.
If a remainder repeats, it means the decimals will start repeating onwards, and we enclose the repeating sequence in parentheses.
Time Complexity: O(d), where d is the length of the repeating sequence in the worst case. This is because each fractional digit is calculated one at a time.
Space Complexity: O(d), for storing seen remainders in the hash map.
1var fractionToDecimal = function(numerator, denominator) {
2 if (numerator === 0) return "0";
3 let result = '';
4 if (numerator < 0 ^ denominator < 0) result += '-';
5 let num = Math.abs(numerator);
6 let den = Math.abs(denominator);
7 result += Math.floor(num / den);
8 let remainder = num % den;
9 if (remainder === 0) return result;
10 result += '.';
11 const map = new Map();
12 while (remainder !== 0) {
13 if (map.has(remainder)) {
14 const pos = map.get(remainder);
15 result = result.slice(0, pos) + '(' + result.slice(pos) + ')';
16 break;
17 }
18 map.set(remainder, result.length);
19 remainder *= 10;
20 result += Math.floor(remainder / den);
21 remainder %= den;
22 }
23 return result;
24};The JavaScript solution similarly employs the long division method and hash map to track remainders and their positions in the result string.
If a remainder repeats, a repeating sequence is detected, and we wrap it with parentheses using slice operations on the string.
JavaScript's dynamic typing system helps handle large numbers during computations.