LeetCode截图

原题

原题链接

解题思路

对题目的理解

  1. Xxx。
  2. Xxx
  3. Xxx

show code

function intToRoman(num: number): string {
  const map = new Map<number, string>([
    [1, 'I'],
    [4, 'IV'],
    [5, 'V'],
    [9, 'IX'],
    [10, 'X'],
    [40, 'XL'],
    [50, 'L'],
    [90, 'XC'],
    [100, 'C'],
    [400, 'CD'],
    [500, 'D'],
    [900, 'CM'],
    [1000, 'M']
  ])
  let result = ''
  let i = num
  while (i > 0) {
    let base = 0
    if (i >= 1) base = 1
    if (i >= 10) base = 10
    if (i >= 100) base = 100
    if (i >= 1000) base = 1000
    const m = Math.floor(i / base)
    const x = m * base

    if (map.has(x)) {
      result += map.get(x)
    } else {
      const symbol = map.get(base)
      if (m > 5) {
        result += `${map.get(base * 5)}${symbol.repeat(m - 5)}`
      } else {
        result += symbol.repeat(m)
      }
    }
    i -= x
  }
  return result
}

总结