跳到主要内容

166.分数到小数

链接:166.分数到小数
难度:Medium
标签:哈希表、数学、字符串
简介:给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以 字符串形式返回小数 。

题解 1 - typescript

  • 编辑时间:2021-10-04
  • 执行用时:72ms
  • 内存消耗:39.6MB
  • 编程语言:typescript
  • 解法介绍:长除法,储存余数。
function fractionToDecimal(numerator: number, denominator: number): string {
let flag = '';
if (numerator * denominator < 0) flag = '-';
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
const integer = `${flag}${Math.floor(numerator / denominator)}`;
let mod = numerator % denominator;
if (mod === 0) return `${integer}`;
const map: Record<number, [number, number]> = {};
let decimal = '';
numerator = mod;
while (true) {
numerator *= 10;
const num = ~~(numerator / denominator);
mod = numerator % denominator;
if (map[mod] !== undefined && map[mod][0] === num) break;
decimal += num;
map[mod] = [num, decimal.length - 1];
if (mod === 0) break;
numerator = mod;
}
if (mod === 0) return `${integer}.${decimal}`;
const [, idx] = map[mod];
if (idx === 0) return `${integer}.(${decimal})`;
return `${integer}.${decimal.substr(0, idx)}(${decimal.substr(idx)})`;
}