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) {
map<char,int> romanToIntMap {
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000},
};
int ret = romanToIntMap[s[s.length()-1]];
for (int i = s.length()-2; i >= 0; --i)
{
if (romanToIntMap[s[i]] < romanToIntMap[s[i+1]])
ret -= romanToIntMap[s[i]];
else
ret += romanToIntMap[s[i]];
}
return ret;
}
};
本文介绍了一种将罗马数字转换为整数的算法实现。通过定义一个映射表存储罗马数字及其对应的整数值,遍历输入字符串并根据相邻字符的大小关系决定加减操作,最终返回整数结果。适用于1到3999范围内的罗马数字。
262

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



