13. 罗马数字转整数
程序员文章站
2023-12-27 18:19:27
...
int nLen = s.length();
bool bAtEnd = false;
bool bAhead = false;
int nSum = 0;
for (int i = 0; i < nLen; i++)
{
char ch = s.at(i);
char chN = 'a';
if (i == nLen - 1)
{
bAtEnd = true;
}
else
{
chN = s.at(i + 1);
}
switch (ch)
{
case 'I':
if (!bAtEnd && (chN == 'V' || chN == 'X') && !bAhead)
{
bAhead = true;
nSum -= 1;
}
else
{
if (bAhead)
{
bAhead = false;
}
nSum += 1;
}
break;
case 'V':
nSum += 5;
if (bAhead)
{
bAhead = false;
}
break;
case 'X':
if (!bAtEnd && (chN == 'L' || chN == 'C') && !bAhead)
{
bAhead = true;
nSum -= 10;
}
else
{
nSum += 10;
if (bAhead)
{
bAhead = false;
}
}
break;
case 'L':
nSum += 50;
if (bAhead)
{
bAhead = false;
}
break;
case 'C':
if (!bAtEnd && (chN == 'D' || chN == 'M') && !bAhead)
{
bAhead = true;
nSum -= 100;
}
else
{
nSum += 100;
if (bAhead)
{
bAhead = false;
}
}
break;
case 'D':
nSum += 500;
if (bAhead)
{
bAhead = false;
}
break;
case 'M':
nSum += 1000;
if (bAhead)
{
bAhead = false;
}
break;
default:
break;
}
}
return nSum;