Description:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:题目是把罗马数字字符串转换为整数,罗马数字由 I、V、X、L、C、D、M 7个基本数字构成,罗马数字与整数转换如下图,通过观察可以得出规律,从右向左遍历, 若 s[i]>=s[i-1],累加当前数字,若
s[i]<s[i-1],则减当前数
![](https://i-blog.csdnimg.cn/blog_migrate/8c764da1481a0bc157bd83dfefdf8b2e.png)
class Solution {
public:
int charToInt(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;
}
return 0;
}
int romanToInt(string s) {
if(s.empty())
return 0;
int index = s.length() - 1;
int pre = charToInt(s[index]);
int ret = pre;
for(int i = index - 1; i >= 0; i--)
{
int tmp = charToInt(s[i]);
if(tmp >= pre)
ret += tmp;
else
ret -= tmp;
pre = tmp;
}
return ret;
}
};