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 res = 0, len = s.length();
map<char, int> hash;
hash.insert(make_pair('I', 1));
hash.insert(make_pair('V',5));
hash.insert(make_pair('X',10));
hash.insert(make_pair('L',50));
hash.insert(make_pair('C',100));
hash.insert(make_pair('D',500));
hash.insert(make_pair('M',1000));
map<char, int>::iterator it1, it2;
res = hash[s[len-1]];
for(int i=len-2;i>=0;i--)
{
it1 = hash.find(s[i]);
it2 = hash.find(s[i+1]);
if(it1->second < it2->second)
res -= it1->second;
else
res += it1->second;
}
return res;
}
};
罗马数字转整数

本文介绍了一种将罗马数字转换为整数的方法。通过使用C++实现了一个Solution类,该类包含一个名为romanToInt的成员函数,能够处理从1到3999范围内的罗马数字。文中展示了如何通过哈希表映射罗马字符到其对应的整数值,并提供了一个逆向遍历字符串的算法来正确计算总和。
689

被折叠的 条评论
为什么被折叠?



