关于javascript:罗马数字转换器

32次阅读

共计 878 个字符,预计需要花费 3 分钟才能阅读完成。

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

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 个,再依照传入数字进行组装,失去最终后果

正文完
 0