[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/niac/JavaScript-Algorithms/master/leetcode/roman-to-integer.js [Back]  [Original]

/**
 *  Question:
 *    Given a roman numeral, convert it to an integer.
 *    Input is guaranteed to be within the range from 1 to 3999.
 *  Tag:
 *    Math, String
 * 
 *       'XLV' == 45
 *  
 *    1. 
 *    2. ,
 *        IXC45VLXLV()
 *        8VIIIIIX )
 * 
 * /

 //
 
var romanToInt = function(s) {
    var rToIMap = {
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000
    }
    var result = rToIMap[s[s.length-1]];
    
    for(var i=s.length-2; i>=0; i--)  {
      var currNum = rToIMap[s[i]],
          afterNum = rToIMap[s[i+1]];
          
        if (currNum >= afterNum) {
          result += currNum;  
        } else {  
          result -= currNum; 
        }
    } 
    
    return result;
};

Web Proxy Viewer  |  New URL  |  Original Page