从最高位到最低位

const roman = {
        4: ['M', 'MM', 'MMM'],
        3: [
          'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'
        ],
        2: [
          'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'
        ],
        1: [
          'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'
        ]
}

 var intToRoman = function (num) {

      let ret = ''
      let digit = ~~Math.log10(num, 10) + 1; //至少有一位
      let divisor = Math.pow(10, digit - 1);

      while (num > 0) {
        var index = Math.floor(num / divisor); //最高位

        ret += roman[digit][index - 1] || "";//处理101的情况

        num -= index * divisor;//去掉最高位

        digit -= 1; //减少层级
        divisor /= 10//减少除数

      }
      return ret;

    };

从最低位到最高位

var symbols = [
    [
        "I",
        "II",
        "III",
        "IV",
        "V",
        "VI",
        "VII",
        "VIII",
        "IX"
    ],
    [
        "X",//10
        "XX",//20
        "XXX",//30
        "XL",//40
        "L",//50
        "LX",//60
        "LXX",//70
        "LXXX",//80
        "XC",//90
    ],
    [
        "C",//100
        "CC",//200
        "CCC",//300
        "CD",//400
        "D",//500
        "DC",//600
        "DCC",//700
        "DCCC",//800
        "CM",//900
    ],
    [
        "M",//1000
        "MM",//2000
        "MMM"//3000
    ]
]
var intToRoman = function (num) {
    var roman = "", digit = 0
    while (num >= 1) {
        var index = num % 10
        var num = Math.trunc(num / 10)
        var romans = symbols[digit]
        var cur = romans[index - 1] || ""
        roman = cur + roman
        digit++
    }
    return roman
};

另一种从高到底

var intToRoman = function(num) {
    const roman = {
    'M':1000,
    'CM':900,
    'D':500,
    'CD':400,
    'C':100,
    'XC':90,
    'L':50,
    'XL':40,
    'X':10,
    'IX':9,
    'V':5,
    'IV':4,
    'I': 1,
    }
    let result = ''

    for(let key in roman){
         //先判定数字在哪个区间中
        if(num >= roman[key]){

            let divisor = Math.trunc(num / roman[key])
            result += key.repeat(divisor)
            num -= roman[key] * divisor
        }
    }
    return result
};
12-22 19:41