把传入的数字转为罗马数字

function convertToRoman(num) {
  let numStr = "" + num,result = "";
  for(let i = 0 ;i<numStr.length;i++){
    result += NumToRoman(parseInt(numStr[i]),numStr.length - i)
  }
  return num;
}

function NumToRoman(num, length) {
  let romanSymbol = ["I", "V", "X", "L", "C", "D", "M"];
  let startIdx = 2 * (length - 1);
  let curSymbol = [];
  for (let i = 0; i < 3; i++) {
    curSymbol.push(romanSymbol[startIdx + i]);
  }
  let result = "";
  switch (num) {
    case 1:
      result = curSymbol[0];
      break;
    case 2:
      result = curSymbol[0] + curSymbol[0];
      break;
    case 3:
      result = curSymbol[0] + curSymbol[0] + curSymbol[0];
      break;
    case 4:
      result = curSymbol[0] + curSymbol[1];
      break;
    case 5:
      result = curSymbol[1];
      break;
    case 6:
      result = curSymbol[1] + curSymbol[0];
      break;
    case 7:
      result = curSymbol[1] + curSymbol[0] + curSymbol[0];
      break;
    case 8:
      result = curSymbol[1] + curSymbol[0] + curSymbol[0] + curSymbol[0];
      break;
    case 9:
      result = curSymbol[0] + curSymbol[2];
      break;
  }
  return result;
}

convertToRoman(36);

思路:根据传入的数字位数,从罗马字符数组里截取3个,再按照传入数字进行组装,得到最终结果


点墨
26 声望3 粉丝

全栈前端开发工程师