Roman Numeral Switch Case没有正确评估

时间:2016-10-31 19:34:44

标签: javascript switch-statement bitwise-operators roman-numerals

我在罗马数字转换功能中得到了意想不到的结果。它将正确评估1,2或4位数字。它还将正确处理4位数字的第3位数字。如果数字是3位数,它会评估百位的位置,就像那个位置一样。

function convertToRoman(num) {

var evaluate = num.toString();
var replace = "";
var oneUnit;
var fiveUnit;
var tenUnit;


for (var i = 0; i < evaluate.length; i++ )
{

switch (evaluate.length | i)
  {
    case 1|0:
    case 2|1:
    case 3|2:
    case 4|3:
      oneUnit = "I";
      fiveUnit = "V";
      tenUnit = "X";
      break;
    case 2|0:
    case 3|1:
    case 4|2:
      oneUnit = "X";
      fiveUnit = "L";
      tenUnit = "C";
      break;
    case 3|0:
    case 4|1:
      oneUnit = "C";
      fiveUnit = "D";
      tenUnit = "M";
      break;
    case 4|0:
      oneUnit = "M";
      fiveUnit = "MMMMM";
      tenUnit = "MMMMMMMMMM";
      break;
  }


switch (evaluate.charAt(i))
{
  case "1":
  replace += oneUnit;
  break;

  case "2":
  replace += oneUnit + oneUnit;
  break;

  case "3":
  replace += oneUnit + oneUnit + oneUnit;
  break;

  case "4":
  replace += oneUnit + fiveUnit;
  break;

  case "5":
  replace += fiveUnit;
  break;

  case "6":
  replace += fiveUnit + oneUnit;
  break;

  case "7":
  replace += fiveUnit + oneUnit + oneUnit;
  break;

  case "8":
  replace += fiveUnit + oneUnit + oneUnit + oneUnit;
  break;

  case "9":
  replace += oneUnit + tenUnit;
  break;
}
}
num = replace;
return num;
}

555的理想回报:“DLV” 返回555:“VVV”

1555的期望回报:“MDLV” 返回1555:“MDLV”

为什么3位数字的前2位数字没有分配到正确的情况?

1 个答案:

答案 0 :(得分:1)

您希望匹配值集,但switch语句只能根据其大小写值计算一个表达式。这里使用了按位OR运算符,因为结果不是evaluate.lengthi的值的串联。您应该将第一个开关块转换为一系列if / else语句。