Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
目前做过的最简单的一道medium的题目,没有数学,没有算法,百度下搞懂罗马数字是怎么回事就行。
不过做完后通过看别人的解题,倒是发现“指针数组”这个不错的数据结构,大大的缩短了代码的长度,大家可以看看下面的对比。程序思想都是一样的。
char* intToRoman(int num) {
char *s = (char *)malloc(sizeof(char) * 20);
strcpy(s , "");
int digit,base;
for(base = 1000; base > 0 ; num %= base, base /= 10)
{
digit = num / base;
switch(digit)
{
case 0: break;
case 1: switch(base){
case 1000: strcat(s, "M"); break;
case 100: strcat(s, "C"); break;
case 10: strcat(s, "X"); break;
case 1: strcat(s, "I"); break;
}
break;
case 2: switch(base){
case 1000: strcat(s, "MM"); break;
case 100: strcat(s, "CC"); break;
case 10: strcat(s, "XX"); break;
case 1: strcat(s, "II"); break;
}
break;
case 3: switch(base){
case 1000: strcat(s, "MMM"); break;
case 100: strcat(s, "CCC"); break;
case 10: strcat(s, "XXX"); break;
case 1: strcat(s, "III"); break;
}
break;
case 4: switch(base){
case 100: strcat(s, "CD"); break;
case 10: strcat(s, "XL"); break;
case 1: strcat(s, "IV"); break;
}
break;
case 5: switch(base){
case 100: strcat(s, "D"); break;
case 10: strcat(s, "L"); break;
case 1: strcat(s, "V"); break;
}
break;
case 6: switch(base){
case 100: strcat(s, "DC"); break;
case 10: strcat(s, "LX"); break;
case 1: strcat(s, "VI"); break;
}
break;
case 7: switch(base){
case 100: strcat(s, "DCC"); break;
case 10: strcat(s, "LXX"); break;
case 1: strcat(s, "VII"); break;
}
break;
case 8: switch(base){
case 100: strcat(s, "DCCC"); break;
case 10: strcat(s, "LXXX"); break;
case 1: strcat(s, "VIII"); break;
}
break;
case 9: switch(base){
case 100: strcat(s, "CM"); break;
case 10: strcat(s, "XC"); break;
case 1: strcat(s, "IX"); break;
}
break;
}
}
return s;
}
char* intToRoman(int num) {
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"};
char *s = (char *)malloc(sizeof(char) * 20);
strcpy(s , "");
int digit,base;
for(base = 1000; base > 0 ; num %= base, base /= 10)
{
digit = num / base;
switch(base)
{
case 1000: strcat(s, chM[digit]); break;
case 100: strcat(s, chC[digit]); break;
case 10: strcat(s, chX[digit]); break;
case 1: strcat(s, chI[digit]); break;
}
}
return s;
}
小结:
1)操作字符串时,记得用strcat等函数,以及合理运用指针数组,可以使代码更简洁高效。