Lesson 4 of 8 · 18 min

Challenge: Roman numerals, both ways

Arjun is visiting a museum in Port Louis. The old clock on the wall shows IV and IX, a foundation stone says MDCCCLXIV, and the film in the cinema room ends with MMXXVI. He wants a little program to translate.

Roman numerals use seven symbols:

Symbol I V X L C D M
Value 1 5 10 50 100 500 1000

Symbols are written from biggest to smallest and added up: MMXXVI is 1000 + 1000 + 10 + 10 + 5 + 1 = 2026.

The twist: a symbol is never repeated four times. Instead, a smaller symbol before a bigger one is subtracted. There are exactly six of these pairs:

IV IX XL XC CD CM
4 9 40 90 400 900

So 1994 is M + CM + XC + IV = MCMXCIV.

Your task

Write two functions:

  1. toRoman(n) turns a whole number from 1 to 3999 into Roman numerals.
  2. fromRoman(text) turns valid Roman numerals back into a number.
toRoman(2026)          // "MMXXVI"
toRoman(1994)          // "MCMXCIV"
toRoman(4)             // "IV"
fromRoman("XIV")       // 14
fromRoman("MCMXCIV")   // 1994

Rules

  • toRoman only gets whole numbers from 1 to 3999.
  • fromRoman only gets valid numerals in capital letters, so you do not need to check for mistakes.
  • fromRoman(toRoman(n)) must give back n for every number from 1 to 3999.

Tips

  • For toRoman, make a list of 13 value/symbol pairs from biggest to smallest, with the six subtractive pairs in their places: [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], ...]. Then take away the biggest value that fits, again and again.
  • For fromRoman, an object like { I: 1, V: 5, X: 10, ... } gives each symbol's value. Look at each symbol together with the next one: if the next is bigger, subtract this one, otherwise add it.
  • text[i + 1] is undefined past the end of the string, so check that i + 1 < text.length first.
main.js
function toRoman(n) {
  // TODO: build the numeral from the biggest symbols down
  return "";
}

function fromRoman(text) {
  // TODO: add up the symbols, subtracting the small ones that come before bigger ones
  return 0;
}

console.log(toRoman(2026));        // should print MMXXVI
console.log(fromRoman("MCMXCIV")); // should print 1994

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…