Skip to content

Commit 56dc330

Browse files
committed
update: 166
1 parent 5d8872f commit 56dc330

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ This is the solutions collection of my LeetCode submissions, most of them are pr
101101
| 162 | [Find Peak Element](https://leetcode.com/problems/find-peak-element/) | [JavaScript](./src/find-peak-element/res.js) | Medium |
102102
| 164 | [Maximum Gap](https://leetcode.com/problems/maximum-gap/) | [JavaScript](./src/maximum-gap/res.js) | Hard |
103103
| 165 | [Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/) | [JavaScript](./src/compare-version-numbers/res.js) | Medium |
104+
| 166 | [fraction-to-recurring-decimal](https://leetcode.com/problems/fraction-to-recurring-decimal/) | [TypeScript](./src/fraction-to-recurring-decimal/res.ts) | Medium |
104105
| 169 | [Majority Element](https://leetcode.com/problems/majority-element/) | [JavaScript](./src/majority-element/res.js) | Easy |
105106
| 175 | [Combine Two Tables](https://leetcode.com/problems/combine-two-tables/) | [SQL](./src/combine-two-tables/res.txt) | Easy |
106107
| 176 | [Second Highest Salary](https://leetcode.com/problems/second-highest-salary/) | [SQL](./src/second-highest-salary/res.txt) | Easy |
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
function fractionToDecimal(numerator: number, denominator: number): string {
2+
if (numerator === 0) {
3+
return '0';
4+
}
5+
6+
let result: string[] = [];
7+
const remainderMap: { [key in number]: number } = {};
8+
9+
if (numerator * denominator < 0) {
10+
result.push('-');
11+
}
12+
numerator = Math.abs(numerator);
13+
denominator = Math.abs(denominator);
14+
15+
const integerPart = Math.floor(numerator / denominator);
16+
result.push(String(integerPart), '.');
17+
numerator = (numerator % denominator) * 10;
18+
19+
while (numerator && numerator < denominator) {
20+
result.push('0');
21+
remainderMap[numerator] = result.length - 1;
22+
numerator *= 10;
23+
}
24+
25+
let currentRemainder = numerator;
26+
while (currentRemainder) {
27+
if (remainderMap[currentRemainder]) {
28+
const remainderIndex = remainderMap[currentRemainder];
29+
const remainderRepeatString = result.slice(remainderIndex).join('');
30+
result = [...result.slice(0, remainderIndex), '(', remainderRepeatString, ')'];
31+
break;
32+
} else {
33+
const newRemainder = currentRemainder % denominator;
34+
const divideItem = Math.floor(currentRemainder / denominator);
35+
remainderMap[currentRemainder] = result.length;
36+
result.push(divideItem.toString());
37+
currentRemainder = newRemainder * 10;
38+
}
39+
}
40+
41+
if (result[result.length-1] === '.' || result.indexOf('.') === 0) {
42+
return result.join('').replace('.', '');
43+
}
44+
45+
return result.join('');
46+
};

0 commit comments

Comments
 (0)