题目链接
https://leetcode.com/problems/roman-to-integer/
注意点
通常情况下,罗马数字中小的数字在大的数字的右边。某几个特例情况下,小的数字在大的数字的左边,此时计算方式有所不同。
解法
解法1:从左往右遍历字符串,依次判断各种正常情况及特例情况。O(n)
int romanToInt(char * s){
int sum = 0;
char * str = s;
while(*str != ' ')
{
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;
}
解法2:从左往右遍历字符串,符合正常情况做加法,特例情况做减法。O(n)
int romanToInt(char * s){
int sum = 0;
char * str = s;
while(*str != ' ')
{
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
",romanToInt(s));
}
return 0;
}
遇到问题
1.纯C如何声明不定长字符串
小结
找规律题?