273.整数转换英文表示
链接:273.整数转换英文表示
难度:Hard
标签:递归、数学、字符串
简介:将非负整数 num 转换为其对应的英文表示。
题解 1 - typescript
- 编辑时间:2021-10-11
- 执行用时:80ms
- 内存消耗:39.6MB
- 编程语言:typescript
- 解法介绍:分块计算。
function numberToWords(num: number): string {
  if (num === 0) return 'Zero';
  const low = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
  const mid = [
    'Ten',
    'Eleven',
    'Twelve',
    'Thirteen',
    'Fourteen',
    'Fifteen',
    'Sixteen',
    'Seventeen',
    'Eighteen',
    'Nineteen',
  ];
  const high = [
    '',
    '',
    'Twenty',
    'Thirty',
    'Forty',
    'Fifty',
    'Sixty',
    'Seventy',
    'Eighty',
    'Ninety',
  ];
  let ans = '';
  let mod = 10 ** 9;
  if (num >= mod) {
    ans += `${format(Math.floor(num / mod))} Billion `;
    num %= mod;
  }
  mod = 10 ** 6;
  if (num >= mod) {
    ans += `${format(Math.floor(num / mod))} Million `;
    num %= mod;
  }
  mod = 10 ** 3;
  if (num >= mod) {
    ans += `${format(Math.floor(num / mod))} Thousand `;
    num %= mod;
  }
  if (num > 0) {
    ans += `${format(num)} `;
  }
  return ans.trimEnd();
  function format(num: number) {
    let ans = '';
    if (num >= 100) {
      ans += `${low[Math.floor(num / 100)]} Hundred `;
      num %= 100;
    }
    const highNum = Math.floor(num / 10);
    const lowNum = num % 10;
    if (highNum >= 2) {
      ans += `${high[highNum]}`;
      if (lowNum > 0) ans += ` ${low[lowNum]} `;
    } else if (highNum === 1) {
      ans += `${mid[num - 10]} `;
    } else {
      ans += `${low[num]} `;
    }
    return ans.trimEnd();
  }
}