给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数。如果小数部分为循环小数,则将循环的部分括在括号内。如果存在多个答案,只需返回 任意一个 。
长除法
- 时间复杂度O(n),空间复杂度O(1)
- Runtime: 99 ms, faster than 16.26%
- Memory Usage: 38.5 MB, less than 93.50%
/**
* @param {number} numerator
* @param {number} denominator
* @return {string}
*/
var fractionToDecimal = function(numerator, denominator) {
if (numerator % denominator === 0) {
return Math.floor(numerator / denominator) + '';
}
// 符号
const res = [];
if (numerator < 0 ^ denominator < 0) {
res.push('-');
}
// 整数部分
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
res.push(Math.floor(numerator / denominator) + '.');
// 小数部分
const frac = [];
const map = new Map();
let remainder = numerator % denominator;
let index = 0;
while (remainder !== 0 && !map.has(remainder)) {
map.set(remainder, index);
remainder *= 10;
frac.push(Math.floor(remainder / denominator));
remainder %= denominator;
index++;
}
if (remainder !== 0) { // 有循环节
let insertIndex = map.get(remainder);
frac.splice(insertIndex, 0, '(');
frac.push(')');
}
res.push(frac.join(''));
return res.join('');
};
网友评论