# 题目链接

https://leetcode.com/problems/roman-to-integer/

# 解法

int romanToInt(char * s){
int sum = 0;
char * str = s;
while(*str != '\0')
{
if(*str == 'M') sum+= 1000;
else if(*str == 'D') sum+= 500;
else if(*str == 'C')
{
if(*(str+1) == 'D')
{
sum += 400;
str = str + 2;
continue;
}
else if(*(str+1) == 'M')
{
sum += 900;
str = str + 2;
continue;
}
else sum += 100;
}
else if(*str == 'L') sum+= 50;
else if(*str == 'X')
{
if(*(str+1) == 'L')
{
sum += 40;
str = str + 2;
continue;
}
else if(*(str+1) == 'C')
{
sum += 90;
str = str + 2;
continue;
}
else sum += 10;
}
else if(*str == 'V') sum+= 5;
else if(*str == 'I')
{
if(*(str+1) == 'V')
{
sum += 4;
str = str + 2;
continue;
}
else if(*(str+1) == 'X')
{
sum += 9;
str = str + 2;
continue;
}
else sum += 1;
}
str++;
}
return sum;
}


int romanToInt(char * s){
int sum = 0;
char * str = s;
while(*str != '\0')
{
if(*str == 'I') sum += 1;
else if(*str == 'V') sum += 5;
else if(*str == 'X') sum += 10;
else if(*str == 'L') sum += 50;
else if(*str == 'C') sum += 100;
else if(*str == 'D') sum += 500;
else if(*str == 'M') sum += 1000;
//判断特例
if((*(str+1) == 'V' || *(str+1) == 'X')&& *str == 'I' ) sum -= 2;
else if((*(str+1) == 'L' || *(str+1) == 'C')&& *str == 'X') sum -= 20;
else if((*(str+1) == 'D' || *(str+1) == 'M')&& *str == 'C') sum -= 200;
str++;
}
return sum;
}


# 测试代码

#include <stdio.h>
int main()
{
char s[100];
while(scanf("%s",&s)!= EOF)
{
printf("%d\n",romanToInt(s));
}

return 0;
}


1.纯C如何声明不定长字符串

# 小结

posted @ 2020-05-17 02:28  陳浴巾  阅读(129)  评论(0编辑  收藏  举报