Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question.
把罗马数字转成阿拉伯整数
C++(85ms):
1 class Solution { 2 public: 3 int romanToInt(string s) { 4 unordered_map<char,int> m ={{'I',1}, 5 {'V',5}, 6 {'X',10}, 7 {'L',50}, 8 {'C',100}, 9 {'D',500}, 10 {'M',1000},}; 11 12 int sum = m[s.back()] ; 13 for (int i = s.size()-2; i >= 0;i-- ){ 14 if (m[s[i]] < m[s[i+1]]) 15 sum -= m[s[i]] ; 16 else 17 sum += m[s[i]] ; 18 } 19 return sum ; 20 } 21 };