Skip to content

Commit d56dd3e

Browse files
authored
Create 166-fraction-to-recurring-decimal.js
1 parent 07b1493 commit d56dd3e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

166-fraction-to-recurring-decimal.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number} numerator
3+
* @param {number} denominator
4+
* @return {string}
5+
*/
6+
const fractionToDecimal = function (numerator, denominator) {
7+
if (numerator === 0) return '0'
8+
let s = ''
9+
if (Math.sign(numerator) !== Math.sign(denominator)) s += '-'
10+
let n = Math.abs(numerator)
11+
const d = Math.abs(denominator)
12+
s += Math.floor(n / d)
13+
n %= d
14+
if (n === 0) return s
15+
s += '.'
16+
const map = {}
17+
while (n !== 0) {
18+
map[n] = s.length
19+
n *= 10
20+
s += Math.floor(n / d)
21+
n %= d
22+
const i = map[n] // repeat starting index
23+
if (i != null) return `${s.slice(0, i)}(${s.slice(i)})`
24+
}
25+
return s
26+
}

0 commit comments

Comments
 (0)