Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution { public: int romanToInt(string s) { char c[7] = {'I','V','X','L','C','D','M'}; int n[7] = {1,5,10,50,100,500,1000}; unordered_map<char,int> map; map.insert(make_pair('I',1)); map.insert(make_pair('V',5)); map.insert(make_pair('X',10)); map.insert(make_pair('L',50)); map.insert(make_pair('C',100)); map.insert(make_pair('D',500)); map.insert(make_pair('M',1000)); int len = s.length(); int num = 0; if(len==1){ num = map[s[0]]; return num; } for(int i = 1; i < len; i++){ if(map[s[i]] <= map[s[i-1]]){ num += map[s[i-1]]; } else{ num+= map[s[i]]-map[s[i-1]]; i++; //dealt two letters at one time, so i should increase 2 } } //Do not forget to discuss the last case independently if(len > 1 && map[s[len-1]] <= map[s[len-2]]){ num+=map[s[len-1]]; } return num; } };
Improve: 使用两个数组代替map,更节省空间。
class Solution { public: int romanToInt(string s) { int values[] = {1000, 500, 100, 50, 10, 5, 1 }; char numerals[] = {'M', 'D', 'C', 'L', 'X', 'V', 'I' }; int i = 0, j = 0, result = 0; while(i < s.length()){ if(s[i] != numerals[j]){ j++; continue; } if(i+1<s.length() && j-1>=0 && s[i+1] == numerals[j-1]){ result += values[j-1]-values[j]; i+=2; } else if(i+1<s.length() && j-2>=0 && s[i+1] == numerals[j-2]){ result += values[j-2]-values[j]; i+=2; } else{ result += values[j]; i++; } } return result; } };