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.

My code:

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    var sum = 0;
    var romanToIntObj = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    };
    var romanArr = s.split("");
    for(let i = 0; i < romanArr.length; i++) {
        var cur, next;
        if(i == romanArr.length - 1) {
            sum += romanToIntObj[romanArr[i]];
        } else {
            cur = romanArr[i];
            next = romanArr[i + 1];
            if(romanToIntObj[cur] < romanToIntObj[next]) {
                sum -= romanToIntObj[cur];
            } else {
                sum += romanToIntObj[cur];
            }
        }
    }
    return sum;
};

Note: 按照每一位判断应该加还是减即可。

你可能感兴趣的:(13. Roman to Integer)