Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999
分析:从后往前扫描字符串,如果S[i+1]大于s[i]则减去s[i],如IV为5-1 = 4,相等或者小于则相加,如VI为5+1 = 6,II为1+1 = 2;
class Solution {
public:
int romanToInt(string s) {
int length = s.length();
if(length <1)
return 0;
map<char,int> m;
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int i = length-1;
int sum = m[s[i--]];
while(i>=0)
if(m[s[i+1]] > m[s[i]])
sum -= m[s[i--]];
else
sum += m[s[i--]];
return sum;
}
};