您的位置:首页 > 其它

[leetcode]13. Roman to Integer

2016-12-28 11:14 253 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999

int trans(char in)
{
switch(in)
{
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
default:return 0;
}
}

int romanToInt(char* s) {
char roman[7]={'I','V','X','L','C','D','M'};
int result = 0;
char tmp;
int mul;
for(int i=0; i<strlen(s); i++)
{
if(i==strlen(s)-1)
tmp=NULL;
else
tmp=s[i+1];
mul=1;
if((s[i]==roman[0]) || (s[i]==roman[2]) || (s[i]==roman[4]))
{
if((s[i]==roman[0]) && ((tmp==roman[1])||(tmp==roman[2])))
mul=-1;
if((s[i]==roman[2]) && ((tmp==roman[3])||(tmp==roman[4])))
mul=-1;
if((s[i]==roman[4]) && ((tmp==roman[5])||(tmp==roman[6])))
mul=-1;
}
result+= trans(s[i]) * mul;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: