
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> hash;
hash['I'] = 1, hash['V'] = 5;
hash['X'] = 10, hash['L'] = 50;
hash['C'] = 100, hash['D'] = 500;
hash['M'] = 1000;
int res = 0;
for (int i = 0; i < s.size(); i ++)
{ // 4xx, 9xx 特例,当前字母比后一个字母小,则-当前字母值, + 后一字母值
if (i + 1 < s.size() && hash[s[i]] < hash[s[i + 1]])
res -= hash[s[i]];
else
res += hash[s[i]];
}
return res ;
}
};
本文介绍了一种将罗马数字转换为整数的C++实现方法。通过使用哈希表映射罗马数字字符到其对应的整数值,并遍历字符串来计算结果。特别处理了特殊情况,如IV(4)和IX(9),确保正确转换。
440

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



