Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
例子:遇到类似IV的数字,扫描到V时,发现V比I大,将最终结果加上V时,应当减去2倍的I。
class Solution {
public:
int romanToInt(string s) {
int result = 0;
for(int i=0;i<s.length();i++){
if(i>=1&&map(s[i-1])<map(s[i])){
result += map(s[i]) - 2*map(s[i-1]);
}else{
result += map(s[i]);
}
}
return result;
}
private:
int map(const char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
};