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) {
int weight[26];
int *map = &weight[-'A'];
map['I'] = 1; map['V'] = 5; map['X'] = 10;
map['L'] = 50; map['C'] = 100; map['D'] = 500;
map['M'] = 1000;
int result = 0;
for (int i=0; i<s.size(); i++) {
if (i != s.size()-1 && map[s[i]] < map[s[i+1]])
result -= map[s[i]];
else
result += map[s[i]];
}
return result;
}
};
转换比较简单, 比后面大或等,则累加;比后面小,则累减。