romanNumeralTranslator

Written on August 16, 2019

문제

Given a roman numeral as input, write a function that converts the roman numeral to a number and outputs it.

Ex:

translateRomanNumeral("LX"); // 60

When a smaller numeral appears before a larger one, it becomes a subtractive operation. You can assume only one smaller numeral may appear in front of larger one.

Ex:

translateRomanNumeral("IV"); // 4

You should return null on invalid input.

풀이

var DIGIT_VALUES = {
  I: 1,
  V: 5,
  X: 10,
  L: 50,
  C: 100,
  D: 500,
  M: 1000
};

var translateRomanNumeral = function(romanNumeral) {
  if (typeof romanNumeral !== "string") {
    return null;
  }
  let number = 0;
  let splited = romanNumeral.split("");
  for (let i = 0; i < splited.length; i++) {
    if (
      i < splited.length - 1 &&
      DIGIT_VALUES[splited[i]] < DIGIT_VALUES[splited[i + 1]]
    ) {
      number -= DIGIT_VALUES[splited[i]];
    } else {
      number += DIGIT_VALUES[splited[i]];
    }
  }
  return number;
};

👩🏻‍💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻‍♀️

in the process of becoming the best version of myself