Roman to Integer---罗马数字转换为十进制整数

Given a roman numeral, convert it to an integer.

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

解题思路,循环遍历罗马数字字符串,从后往前,字母换成对应的数字,如果这个数字小于它后边的数字,则减去,如果大于,则加上.与此题相对应的题目则是整数转换为罗马数字,思路相反.

var romanToInt = function(s) {
    var romanIntJson = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000};
    var intNum = 0;
    for(var i=s.length-1;i>=0;i--){
        if(!intNum){
            intNum = romanIntJson[s[i]];
            continue;
        }
        if(romanIntJson[s[i]] >= romanIntJson[s[i + 1]]){
            intNum+= romanIntJson[s[i]];
        }else{
            intNum -= romanIntJson[s[i]];
        }
    }
    return intNum;
};


你可能感兴趣的:(JavaScript,JavaScript,leetcode,遍历,string)