[LeetCode][JavaScript]Roman to Integer

Roman to Integer

Given a roman numeral, convert it to an integer.

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

https://leetcode.com/problems/roman-to-integer/

 

 


 

 

罗马数字转阿拉伯数字。

从后往前扫,如果当前的数大于之前的数,加上这个数,反之减去当前的数。

 1 /**
 2  * @param {string} s
 3  * @return {number}
 4  */
 5 var romanToInt = function(s) {
 6     var map = {};
 7     map["I"] = 1; map["V"] = 5; map["X"] = 10; map["L"] = 50;
 8     map["C"] = 100; map["D"] = 500; map["M"] = 1000;
 9     var res, tmp = 0;
10     for(var i = s.length - 1; i >= 0; i--){
11         if(!res){
12             res = map[s[i]];
13             continue;
14         }
15         if(map[s[i]] >= map[s[i + 1]]){
16             res += map[s[i]];
17         }else{
18             res -= map[s[i]];
19         }
20     }
21     return res;
22 };

 

posted @ 2015-08-30 00:40  `Liok  阅读(520)  评论(0编辑  收藏  举报