#include <cstdio>
#include <cassert>
#include <iomanip>
#include <list>
#include <iterator>
#include <string>
#include <iostream>
using namespace std;
void Arabic2Roman(int arabic, list<char> & roman)
{
......
}
struct Exception
{
};
int Alpha2Bit(char alpha)
{
switch (alpha)
{
case 'I':
{
return 0;
}
case 'V':
{
return 1;
}
case 'X':
{
return 2;
}
case 'L':
{
return 3;
}
case 'C':
{
return 4;
}
case 'D':
{
return 5;
}
case 'M':
{
return 6;
}
default:
{
throw Exception();
return -1;
}
}
}
int Roman2Arabic(const list<char> & roman)
{
static int const base[] =
{
1, 10, 100, 1000
};
int arabic = 0;
int lastbit = 7;
list<char>::const_reverse_iterator iter = roman.rbegin();
while (iter != roman.rend())
{
int bit = Alpha2Bit(*iter);
if (bit >= lastbit)
{
throw Exception();
return -1;
}
int factor = 0;
if (0 == bit % 2)
{
list<char>::const_reverse_iterator tmpiter = iter;
++tmpiter;
if (tmpiter != roman.rend())
{
switch (Alpha2Bit(*tmpiter) - bit)
{
case 0:
{
factor = 2;
iter = tmpiter;
++tmpiter;
if (tmpiter != roman.rend() && Alpha2Bit((*tmpiter)) == bit)
{
++factor;
iter = tmpiter;
}
break;
}
case 1:
{
factor = 4;
iter = tmpiter;
break;
}
case 2:
{
factor = 9;
iter = tmpiter;
break;
}
default:
{
factor = 1;
break;
}
}
}
else
{
factor = 1;
}
lastbit = bit;
}
else
{
factor = 5;
list<char>::const_reverse_iterator tmpiter = iter;
++tmpiter;
while (tmpiter != roman.rend() && Alpha2Bit(*tmpiter) == bit - 1 && factor < 8)
{
++factor;
iter = tmpiter;
++tmpiter;
}
lastbit = bit - 1;
}
arabic += factor * base[lastbit / 2];
++iter;
}
if (0 == arabic)
{
throw Exception();
return -1;
}
else
{
return arabic;
}
}
int main()
{
for (int i = 1; i < 4000; ++i)
{
try
{
list<char> roman;
Arabic2Roman(i, roman);
int arabic = Roman2Arabic(roman);
if (arabic != i)
{
cout << "error conversion : " << endl << '\t';
}
cout << setw(4) << i << " -> ";
for (list<char>::reverse_iterator iter = roman.rbegin(); iter != roman.rend();)
{
cout << (*iter);
++iter;
}
cout << " -> " << arabic << endl;
if (arabic != i)
{
cin.get();
}
}
catch (Exception & e)
{
cout << "converse " << i << " throw exception" << endl;
cin.get();
}
}
cout << "input roman number:";
string alpha;
while (cin >> alpha)
{
list<char> roman;
for (string::reverse_iterator iter = alpha.rbegin(); iter != alpha.rend(); ++iter)
{
roman.push_back(*iter);
}
try
{
int arabic = Roman2Arabic(roman);
cout << '\t' << arabic << endl;
}
catch (Exception & e)
{
cout << '\t' << "can not converse " << alpha << endl;
}
}
return 0;
}
其中Arabic2Roman()在 试题:将阿拉伯数字转为罗马数字 中有给出实现代码