Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
基本字符 | I | V | X | L | C | D | M |
阿拉伯数字 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 map<char,int> hash; 5 hash[‘I‘] = 1; 6 hash[‘V‘] = 5; 7 hash[‘X‘] = 10; 8 hash[‘L‘] = 50; 9 hash[‘C‘] = 100; 10 hash[‘D‘] = 500; 11 hash[‘M‘] = 1000; 12 13 int result=hash[s[0]]; 14 for(int i=1;i<s.length();i++) 15 { 16 int pre=hash[s[i-1]]; 17 int cur=hash[s[i]]; 18 if(pre>=cur) 19 { 20 result+=cur; 21 } 22 else 23 { 24 result+=cur-2*pre; 25 } 26 27 } 28 return result; 29 } 30 };
原文:http://www.cnblogs.com/reachteam/p/4183575.html