Skip to content

Latest commit

 

History

History
112 lines (100 loc) · 2.68 KB

12.integer-to-roman.md

File metadata and controls

112 lines (100 loc) · 2.68 KB

整数转罗马数字

题目

思路

1 2 3 4 5 6 7 8 9 10
I II III IV V VI VII VIII IX X
XI XII XIII XIV XV XVI XVII XVIII XIX XX
XXI XXII XXIII XXIV XXV XXVI XXVII XXVIII XXIX XXX
XXXI XXXII XXXIII XXXIV XXXV XXXVI XXXVII XXXVIII XXXIX L

可设置一个转换表, 按10的倍数进行划分, 将数值转换为对应的字符.

{
  1: 'I',
  5: 'V',
  10: 'X',
  50: 'L',
  100: 'C',
  500: 'D',
  1000: 'M'
}

数字则按照1000, 100, 10, 1开始进行除法操作, 而后向下取整, 根据这个值来生成对应的模板, 从而最终生成所需的值, 值的情况一般有以下五种

X表示当前的字符, X+1则表示下一个字符, X+2则表示下个字符的下个字符

数值 字符
0
1 {X}
2 {X}{X}
3 {X}{X}{X}
4 {X}{X+1}
5 {X+1}
6 {X+1}{X}
7 {X+1}{X}{X}
8 {X+1}{X}{X}{X}
9 {X}{X+2}

以下是934的转换过程

序号 运算过程 数字结果 字符结果
1 934
2 934 / 1000 = 0 934
3 934 / 100 = 9 934 - (100 * 9) = 34 CM
4 34 / 10 = 3 34 - (10 * 3) = 4 CMXXX
5 4 / 1 = 4 4 - (1 * 4) = 0 CMXXXIV
/**
 * @param {number} num
 * @return {string}
 */
var intToRoman = function(num) {
  const INT_ROMAN_MAP = {
    1: 'I',
    5: 'V',
    10: 'X',
    50: 'L',
    100: 'C',
    500: 'D',
    1000: 'M'
  }

  const INTS = Object.keys(INT_ROMAN_MAP).map(Number)
  let str = ''
  let divisor = 1000
  while (divisor >= 1) {
    const n = Math.floor(num / divisor)
    num = num - (divisor * n)
    const x = INTS.findIndex(n => divisor === n)
    switch (n) {
      case 1:
        str = str + INT_ROMAN_MAP[INTS[x]]
        break
      case 2:
        str = str + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]]
        break
      case 3:
        str = str + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]]
        break
      case 4:
        str = str + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x + 1]]
        break
      case 5:
        str = str + INT_ROMAN_MAP[INTS[x + 1]]
        break
      case 6:
        str = str + INT_ROMAN_MAP[INTS[x + 1]] + INT_ROMAN_MAP[INTS[x]]
        break
      case 7:
        str = str + INT_ROMAN_MAP[INTS[x + 1]] + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]]
        break
      case 8:
        str = str + INT_ROMAN_MAP[INTS[x + 1]] + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x]]
        break
      case 9:
        str = str + INT_ROMAN_MAP[INTS[x]] + INT_ROMAN_MAP[INTS[x + 2]]
        break
    }

    divisor = divisor / 10
  }
  return str
};