把罗马数字转为十进制 #JS_codewar_9

题目

Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.

Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.

Example:

solution('XXI'); // should return 21

我的代码

function solution(roman){
  // complete the solution by transforming the 
  // string roman numeral into an integer  
  let bucket = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1};
  let roman_array = roman.split('').map(function(x){return bucket[x]});
  console.log(roman_array);
  for (i = 0; i < roman_array.length - 1; i++) {
      if (roman_array[i] - roman_array[i+1] >= 0) {
          roman_array[i] = "+" + roman_array[i];
      } else {
          roman_array[i] = "-" + roman_array[i];
      }
  }
  roman_array[roman_array.length - 1] = "+" + roman_array[roman_array.length - 1];
  console.log(roman_array);
  let result = roman_array.reduce(function(acc, val){return acc*1 + val*1});
  console.log(result);
  return result;
}

别人的代码

function solution(roman)
{
  var data = {M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1};
  var numbers = roman.split('');
  var sum = 0, i;

  for(i = 0; i < numbers.length; i++)
  {
    if(data[numbers[i]] < data[numbers[i+1]])
    {
      sum += data[numbers[i+1]] - data[numbers[i]];
      i++;
    }
    else
    {
      sum += data[numbers[i]];
    }
  }
  
  return sum;
}

我的感想

看别人的代码,发现不用去在意遍历时,如果i+1超出了范围会怎么样,反正一样是false
把唯一的情况(相减),写成if,其余都被包含在else里了。

别人的代码2

function solution(roman){
    var rom ={ "I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000};
    return roman.split('').reverse().reduce(
        function(dec,c,i,rr){ 
            c=rom[c];
            i=rom[rr[i-1]]||0; 
            return dec + (i<=c? c: -c) }
        ,0
    )
}

我的感想

暂时没看明白……

你可能感兴趣的:(把罗马数字转为十进制 #JS_codewar_9)