-
Notifications
You must be signed in to change notification settings - Fork 154
/
fraction-to-recurring-decimal.js
85 lines (70 loc) · 1.68 KB
/
fraction-to-recurring-decimal.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Fraction to Recurring Decimal
*
* Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
*
* If the fractional part is repeating, enclose the repeating part in parentheses.
*
* Example 1:
*
* Input: numerator = 1, denominator = 2
* Output: "0.5"
* Example 2:
*
* Input: numerator = 2, denominator = 1
* Output: "2"
* Example 3:
*
* Input: numerator = 2, denominator = 3
* Output: "0.(6)"
*/
/**
* @param {number} numerator
* @param {number} denominator
* @return {string}
*/
const fractionToDecimal = (numerator, denominator) => {
// zero denominator
if (denominator === 0) {
return 'NaN';
}
// zero numerator
if (numerator === 0) {
return '0';
}
const result = [];
// determine the sign
if ((numerator < 0) ^ (denominator < 0)) {
result.push('-');
}
// remove sign of operands
const n = Math.abs(numerator);
const d = Math.abs(denominator);
// append integral part
result.push(Math.floor(n / d));
// in case no fractional part
if (n % d == 0) {
return result.join('');
}
result.push('.');
const map = new Map();
// simulate the division process
for (let r = n % d; r > 0; r %= d) {
// meet a known remainder
// so we reach the end of the repeating part
if (map.has(r)) {
result.splice(map.get(r), 0, '(');
result.push(')');
break;
}
// the remainder is first seen
// remember the current position for it
map.set(r, result.length);
r *= 10;
// append the quotient digit
result.push(Math.floor(r / d));
}
return result.join('');
};
const result = fractionToDecimal(1, 333);
console.log(result);