題目
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
分析
上題說過羅馬數(shù)字和整數(shù)之間的轉(zhuǎn)化問題,現(xiàn)在反過來將羅馬數(shù)字轉(zhuǎn)化為阿拉伯?dāng)?shù)字時(shí)候,反過來考慮篮愉,依次匹配各個(gè)數(shù)位害捕,之后相加得到答案。
bool equal(char *s,int i,char *a)
{
bool ans=true;
int j=0;
while(a[j]!='\0')
{
if(s[i]=='\0'||(s[i]!='\0'&&s[i]!=a[j]))
{
ans=false;
break;
}
j++;
i++;
}
return ans;
}
int romanToInt(char* s) {
char* c[4][10]={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
int ans=0,length=0,i=0,j=0;
for(i=3;i>=0;i--)
{
if(equal(s,length,c[3][i]))
{
ans+=i*1000;
length+=i;
break;
}
}
for(j=2;j>=0;j--)
{
for(i=9;i>0;i--)
{
if(equal(s,length,c[j][i]))
{
// printf("%d %d %d\n",length,i,j);
if(j==2)ans+=i*100;
if(j==1)ans+=i*10;
if(j==0)ans+=i;
if(i==1||i==5)length+=1;
if(i==2||i==4||i==6||i==9)length+=2;
if(i==3||i==7)length+=3;
if(i==8)length+=4;
}
}
}
return ans;
}