LeetCode每日一练【12】

LeetCode -- Integer to Roman

除数计数法

思路:

  1. 将所有罗马数字和数字的映射关系存储到对象中
  2. 依次使用罗马数字对应的数字数组romanVals与参数数字进行除法操作(获取罗马数字重复次数digit)和求余操作(判断罗马数字的类型)
  3. 根据获得到的罗马数字对应的数字value, 返回罗马数字, 然后再进行重复, 加入的结果字符串res
/*
 * @Author: fox
 * @Date: 2022-04-29 10:27:49
 * @LastEditors: fox
 * @LastEditTime: 2022-04-29 11:49:56
 * @Description: https://leetcode.com/problems/integer-to-roman/
 */
/**
 * @description: 经过测试,这并不是一个很好的方案,效率有点低
 * @param {number} num 整型数字
 * @return {string} 罗马数字
 */
const Roman = {
  I: 1,
  IV: 4,
  V: 5,
  IX: 9,
  X: 10,
  XL: 40,
  L: 50,
  XC: 90,
  C: 100,
  CD: 400,
  D: 500,
  CM: 900,
  M: 1000,  
};
const intToRoman = (num) => {
    let digit; // 个数
    let res = ''; // 返回字符串
    const romanVals = Object.values(Roman) // 罗马数字的value数组
    
    for (let i = romanVals.length - 1; i >= 0 && num > 0; i--) {
        digit = Math.floor(num / romanVals[i]) // 获取罗马数字的个数
        res += findKey(romanVals[i]).repeat(digit) // 复制罗马数字
        num %= romanVals[i] // 计算余数
    }

    return res
};

/**
 * @description: 根据对象的value返回对应的key
 * @param {*} value value
 * @param {*} compare 比较函数
 * @param {*} b
 * @return {*}
 */
const findKey = (value, compare = (a, b) => a === b) => {
    return Object.keys(Roman).find(index => {
        return compare(value, Roman[index])
    })
};

let value;

value = 3;
console.log(intToRoman(value)); // III

value = 58;
console.log(intToRoman(value)); // LVIII

value = 1994;
console.log(intToRoman(value)); // MCMXCIV
posted @ 2022-04-29 16:24  白い故雪  阅读(17)  评论(0编辑  收藏  举报