all articles

leetcode war 13 - Roman to Integer

2017-09-26 @sunderls

leetCode js

https://leetcode.com/problems/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.

analysis

This is the reverse problem of Integer to Roman.

The key problem is to handle:

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

we just traverse the digits, and check above patterns while looping.

first trial

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    var numbers = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    };

    var result = 0;
    var tmp = 0;
    for (var i = 0, total = s.length; i < total; i++) {
        tmp = numbers[s[i]];

        if ((s[i] === 'I' && (s[i + 1] === 'V' || s[i + 1] === 'X')) ||
            (s[i] === 'X' && (s[i + 1] === 'L' || s[i + 1] === 'C')) ||
            (s[i] === 'C' && (s[i + 1] === 'D' || s[i + 1] === 'M'))
            ) {
            tmp *= -1;
        }
        result += tmp;
    }

    return result;
};

it just passed. but ran only bottom 40%. how can we improve?