13. Roman to Integer

Description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution

/**
 * Solved with hash table
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    "use strict";
    let table = {
        "IV": 4,
        "IX": 9,
        "XL": 40,
        "XC": 90,
        "CD": 400,
        "CM": 900,
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000,
    };
    let result = 0;
    let i = 0;
    while (i < s.length) {
        if (table[s[i]+s[i+1]]) {
            result += table[s[i]+s[i+1]];
            i += 2;
        } else {
            result += table[s[i]];
            i++;
        }
    }
    return result;
};

results matching ""

    No results matching ""