class Solution {
public:
int romanToInt(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int res = 0;
int prev = 1001;
int cur = 0;
int len = s.size();
for (int i = 0; i < len; ++i)
{
cur = map(s[i]);
if (cur <= prev)
res += cur;
else
{
res += cur;
res -= 2 * prev;
}
prev = cur;
}
return res;
}
int map(char c)
{
switch (c)
{
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
};[Leetcode] Roman to Integer
最新推荐文章于 2019-03-02 17:08:52 发布
本文介绍了一种使用C++实现的将罗马数字字符串转换为整数的方法。通过定义字符映射和遍历输入字符串,该算法能正确处理罗马数字的特殊组合规则,如IV表示4。文中提供了一个名为Solution的类,包含两个主要成员函数:romanToInt用于进行转换,map函数则负责字符到数值的映射。
624

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



