Back to Freecodecamp

Challenge 28: Roman Numeral Parser

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68adce01c0e1144d0a90295c.md

latest1.7 KB
Original Source

--description--

Given a string representing a Roman numeral, return its integer value.

Roman numerals consist of the following symbols and values:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000
  • Numerals are read left to right. If a smaller numeral appears before a larger one, the value is subtracted. Otherwise, values are added.

--hints--

parseRomanNumeral("III") should return 3.

js
assert.equal(parseRomanNumeral("III"), 3);

parseRomanNumeral("IV") should return 4.

js
assert.equal(parseRomanNumeral("IV"), 4);

parseRomanNumeral("XXVI") should return 26.

js
assert.equal(parseRomanNumeral("XXVI"), 26);

parseRomanNumeral("XCIX") should return 99.

js
assert.equal(parseRomanNumeral("XCIX"), 99);

parseRomanNumeral("CDLX") should return 460.

js
assert.equal(parseRomanNumeral("CDLX"), 460);

parseRomanNumeral("DIV") should return 504.

js
assert.equal(parseRomanNumeral("DIV"), 504);

parseRomanNumeral("MMXXV") should return 2025.

js
assert.equal(parseRomanNumeral("MMXXV"), 2025);

--seed--

--seed-contents--

js
function parseRomanNumeral(numeral) {

  return numeral;
}

--solutions--

js
function parseRomanNumeral(numeral) {
  const romanMap = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1000
  };

  let total = 0;

  for (let i = 0; i < numeral.length; i++) {
    const current = romanMap[numeral[i]];
    const next = romanMap[numeral[i + 1]];

    if (next && current < next) {
      total -= current;
    } else {
      total += current;
    }
  }

  return total;
}