罗马数字和阿拉伯数字的装换。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int mp[100];
int val[]={1000,900,500,400,100,90,50,40,10,9,5,4,1};
string r[]={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
map<string, int> roman;
void init()
{
mp['I']=1;
mp['V']=5;
mp['X']=10;
mp['L']=50;
mp['C']=100;
mp['D']=500;
mp['M']=1000;
return;
}
int r2n(char *str)
{
int re, pre;
re = pre = mp[str[0]];
for(int i = 1; str[i]; i++)
{
if(mp[str[i]] <= pre) re += mp[str[i]];
else re = re - 2 * pre + mp[str[i]];
pre = mp[str[i]];
}
return re;
}
string n2r(int k)
{
int i = 0;
string re = "";
while(k > 0)
{
while(k >= val[i])
{
re += r[i];
k -= val[i];
}
i++;
}
return re;
}
int main()
{
init();
for(int i = 1; i < 4000; i++) roman[n2r(i)] = i;
char data[105];
while(gets(data))
{
int t = roman[data];
if(!t) puts("This is not a valid number");
else printf("%d\n", t);
}
return 0;
}