题目:
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 result = 0;
int i;
map<char, int>m;
m['M'] = 1000;
m['D'] = 500;
m['C'] = 100;
m['L'] = 50;
m['X'] = 10;
m['V'] = 5;
m['I'] = 1;
for (i = 0; i<s.size() - 1; ++i) {
if (m[s[i]]<m[s[i + 1]])//左边数小要减
result -= m[s[i]];
else
result += m[s[i]];
}
result += m[s[i]];
return result;
}
};