int romanToInt(char* s)
{
int I = 1;
int V = 5;
int X = 10;
int L = 50;
int C = 100;
int D = 500;
int M = 1000;
int result = 0;
int index = 0;
int buff[20];
int i = 0;
int temp = 0;
while(s[index] != ' ')
{
switch (s[index])
{
case 'I':buff[index] = I;
break;
case 'V':buff[index] = V;
break;
case 'X':buff[index] = X;
break;
case 'L':buff[index] = L;
break;
case 'C':buff[index] = C;
break;
case 'D':buff[index] = D;
break;
case 'M':buff[index] = M;
break;
}
index++;
}
// for(i = 0;i < index;i++)
// {
// printf("%d",buff[i]);
// }
// printf("
index = %d",index);
i = 0;
if(index == 1)
{
return result = buff[i];
}
while(i < index)
{
if(buff[i] < buff[i+1])
{
temp=buff[i+1] - buff[i];
i++;
}
else if(buff[i] == buff[i+1])
{
temp = buff[i] + buff[i+1];
i++;
}
else
{
temp = buff[i];
}
i++;
result = result + temp;
if(i == (index - 1))
{
result = result + buff[i];
break;
}
}
return result;
}
反思:
1 因为我是用数组做的,所以在运行过程中一定要注意会不会出现数组的范围不够,或者是出现下标越界。我一开始提交的代码中没有下面这几行语句
if(index == 1)
{
return result = buff[i];
}
这样就会造成数组下标越界。