Question

0013 - roman to integer

Roman numerals are represented by seven different symbols:
I  V  X  L  C  D  M

SymbolValue
I1
V5
X10
L50
C100
D500
M1000
input: s = III
Output: 3
Expl: III = 3
input: s = LVIII
Output: 58
Expl: L = 50, V = 5, III = 3
input: s = MCMXCIV
Output: 1994
Expl: M = 1000, CM = 900, XC = 90, IV = 4
  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Solution

export default function romanToInt(s: string): number {
  console.log("s: ", s);
  // ============================================================================
  // 1. Handle edge cases
  // ----------------------------------------------------------------------------
  // if               s is empty
  // then             return 0
  // ----------------------------------------------------------------------------
  if (s.length === 0) {
    console.log("S IS EMPTY");
    return 0;
  } else {
    const mapSymbolValue = new Map([
      ["I", 1],
      ["IV", 4],
      ["V", 5],
      ["IX", 9],
      ["X", 10],
      ["XL", 40],
      ["L", 50],
      ["XC", 90],
      ["C", 100],
      ["CD", 400],
      ["D", 500],
      ["CM", 900],
      ["M", 1000],
    ]);
    // ============================================================================
    // 2. Try examples
    // ----------------------------------------------------------------------------
    //
    // ============================================================================
    // 3. Define romanToInt
    // ----------------------------------------------------------------------------
    return 0;
  }
}

Testing