Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
1 class Solution { 2 public: 3 map<char, int> m; 4 int romanToInt(string s) { 5 m.insert(pair<char, int>('I', 1)); 6 m.insert(pair<char, int>('V', 5)); 7 m.insert(pair<char, int>('X', 10)); 8 m.insert(pair<char, int>('L', 50)); 9 m.insert(pair<char, int>('C', 100)); 10 m.insert(pair<char, int>('D', 500)); 11 m.insert(pair<char, int>('M', 1000)); 12 map<char, int>::iterator ite; 13 int len = s.size(); 14 char current; 15 char pre; 16 int temp = 0; 17 int result=0; 18 pre = s[0]; 19 temp = m[pre]; 20 for (int i = 1; i<s.size(); i++) 21 { 22 current = s[i]; 23 if (m[current]==m[pre]) 24 { 25 temp += m[current]; 26 } 27 else 28 { 29 if (m[current] > m[pre]) 30 { 31 temp = m[current] - temp; 32 } 33 else 34 { 35 result += temp; 36 temp = m[current]; 37 } 38 } 39 pre = current; 40 } 41 return result+temp; 42 } 43 44 };