algorithm icon indicating copy to clipboard operation
algorithm copied to clipboard

13. 罗马数字转整数

Open JesseZhao1990 opened this issue 6 years ago • 0 comments

image image image

/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    let hash = {'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}
    let arr = s.split('');
    let sum = 0;
    
    for(let i=0;i<arr.length;i++){
        if(arr[i+1] && hash[arr[i]]<hash[arr[i+1]]){
            let temp = `${arr[i]}${arr[i+1]}`
            sum += hash[temp]
            i++
        }else{
            sum += hash[arr[i]]
        }
    }
    
    return sum
    
};

JesseZhao1990 avatar Oct 19 '19 14:10 JesseZhao1990