Roman to Integer

来源:互联网 发布:淘宝客服外包服务 编辑:程序博客网 时间:2024/06/06 15:50

Given a roman numeral, convert it to an integer.

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

根据上次题目的想法,弄一个字符指针数组,对s进行扫描的过程中,查找是否与数组里对应的字符串匹配。如果匹配上,即可得到相应数位的值。

本身一道简单题,思路很快就有了,但是却花了好久时间,一些细节上的问题还是开始没注意到,还得多编程,积累基本功啊!

同样这道题AC的运行时间是比较长的,我觉得可能是在暂存的字符串与指针数组中字符串比较的过程中浪费了一些时间,但除此之外也没有想到更好的解法,还请大家多多指教。

C语言代码如下:

int romanToInt(char *s) {char *chM[] = {"","M","MM","MMM"};char *chC[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};char *chX[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};char *chI[] = {"","I","II","III","IV","V","VI","VII","VIII","IX"};int n = 0;int i;char *tmp = (char *)malloc(sizeof(char) * 5);char *head = tmp;while(*s != '\0'){tmp = head;*tmp = *s;if(*s == 'M'){while(*(s + 1) == 'M')*++tmp = *++s;*++tmp = '\0';s++;for(i = 0; i < 10; i++)if(!strcmp(head, chM[i]))<span style="white-space:pre"></span>//be careful to use 'head' not 'tmp' herebreak;if(i >= 10)return 0;n += i * 1000;continue;}if(*s == 'C' || *s == 'D'){while(*(s + 1) == 'C' || *(s + 1) == 'D' || *(s + 1) == 'M')*++tmp = *++s;*++tmp = '\0';s++;for(i = 0; i < 10; i++)if(!strcmp(head, chC[i]))break;if(i >= 10)return 0;n += i * 100;continue;}if(*s == 'X' || *s == 'L'){while(*(s + 1) == 'X' || *(s + 1) == 'L' || *(s + 1) == 'C')*++tmp = *++s;*++tmp = '\0';s++;for(i = 0; i < 10; i++)if(!strcmp(head, chX[i]))break;if(i >= 10)return 0;n += i * 10;continue;}if(*s == 'I' || *s == 'V'){while(*(s + 1) == 'I' || *(s + 1) == 'V' || *(s + 1) == 'X')*++tmp = *++s;*++tmp = '\0';s++;for(i = 0; i < 10; i++)if(!strcmp(head, chI[i]))break;if(i >= 10)return 0;n += i;continue;}}return n;}
小结:

1)用指针操控字符串时,一定要冷静的搞清楚指针当前指向的地方,是指向字符串首,还是已经通过++或--操作指向了字符串的其他部分。

2)注意循环中的continue;用法,使用continue语句后将跳过循环的余下部分,进入下一次循环。




0 0