传递罗马数字以获得输出

时间:2017-03-31 01:48:44

标签: javascript decimal roman-numerals

所以我几乎完成了将十进制数字转换为罗马数字以执行算术运算的代码。现在,如果我传递100 + 200 = CCC,这是正确的300.但是,我如何调整我的代码,使其接受以下模式 -

C + CC = CCC

(function toRoman(num1, sign, num2) {
var r1 = '',
    r2 = '',
    decimals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
    roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];

    var translateRomanNumeral = function(num1) {
        for (var k = 0; k < num1.length; k++) {
            if (!(num1[k] in decimals)) {
            return null;
           }
        }
     }

    if (typeof num1 == 'string') {
        num1 = translateRomanNumeral(num1);
    }

   var translateRomanNumeral2 = function(num2) {
       for (var l = 0; l < num2.length; l++) {
          if (!(num2[l] in decimals)) {
          return null;
          }
        }
      }

  if (typeof num2 == 'string') {
     num2 = translateRomanNumeral2(num2);
  }     


for (var i = 0; i < decimals.length; i++) {
    while (num1 >= decimals[i]) {
      r1 += roman[i];
      num1 -= decimals[i];
      }
    }

for (var j = 0; j < decimals.length; j++) {
    while (num2 >= decimals[j]) {
      r2 += roman[j];
      num2 -= decimals[j];
     }
   }

switch (sign) {
    case "+": return r1 + r2;
    case "-": return r1 - r2;
    case "*": return r1 * r2;
    default: return r1 / r2;
   }
return r1, sign, r2;

})('C', '+', 'CC');  

0 个答案:

没有答案