码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 12. Integer to Roman

时间:2019-12-14 18:51:47      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:trunc   roman   dig   rom   dex   repeat   区间   pow   数字   

从最高位到最低位

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
};

leetcode 12. Integer to Roman

标签:trunc   roman   dig   rom   dex   repeat   区间   pow   数字   

原文地址:https://www.cnblogs.com/rubylouvre/p/12040297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!