题目描述:
思路:
多个switch-case嵌套即可,注意题目中的六种特例情况。
class Solution {
public:
int romanToInt(string s) {
int sum = 0;
for(int i = 0; i < s.length(); i++)
{
switch (s[i])
{
case 'I':
if (s[i+1] != 'V' && s[i+1] != 'X')
sum += 1;
else
{
switch (s[i+1])
{
case 'V':
sum += 4;
break;
case 'X':
sum += 9;
break;
}
i++;
}
break;
case 'V':
sum += 5;
break;
case 'X':
if (s[i+1] != 'L' && s[i+1] != 'C')
sum += 10;
else
{
switch (s[i+1])
{
case 'L':
sum += 40;
break;
case 'C':
sum += 90;
break;
}
i++;
}
break;
case 'L':
sum += 50;
break;
case 'C':
if (s[i+1] != 'D' && s[i+1] != 'M')
sum += 100;
else
{
switch (s[i+1])
{
case 'D':
sum += 400;
break;
case 'M':
sum += 900;
break;
}
i++;
}
break;
case 'D':
sum += 500;
break;
case 'M':
sum += 1000;
break;
}
}
return sum;
}
};