Skip to content

Commit e4960e1

Browse files
committed
Add solution #166
1 parent f82a0ec commit e4960e1

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@
152152
162|[Find Peak Element](./0162-find-peak-element.js)|Medium|
153153
164|[Maximum Gap](./0164-maximum-gap.js)|Medium|
154154
165|[Compare Version Numbers](./0165-compare-version-numbers.js)|Medium|
155+
166|[Fraction to Recurring Decimal](./0166-fraction-to-recurring-decimal.js)|Medium|
155156
167|[Two Sum II - Input Array Is Sorted](./0167-two-sum-ii-input-array-is-sorted.js)|Easy|
156157
168|[Excel Sheet Column Title](./0168-excel-sheet-column-title.js)|Easy|
157158
169|[Majority Element](./0169-majority-element.js)|Easy|
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)