本周的题目是一道经典题,难度级别"Medium"...
题目:将1~3999的阿拉伯数字转化为罗马数字。
这题还是比较经典的,做这题之前要先了解一下罗马数字,然后看看实现代码:
char* intToRoman(int num) {
int numArr[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
char *numRoman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
char *numResult = malloc(100);
for(int i=0; i= numArr[i]){
strcat(numResult,numRoman[i]);
num -= numArr[i];
}
}
return numResult;
}
百度百科的罗马数字里面就有这道经典的算法题,不过里面是用C++写的,在这里我也翻译成C,顺便用了个for循环,不易出错:
char* intToRoman(int num)
char* c[4][10]={
{"","I","II","III","IV","V","VI","VII","VIII","IX"},
{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},
{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},
{"","M","MM","MMM"}
};
char *roman = malloc(100);
for (int i = 3; i >= 0; i--) {
int temp = pow(10, i);
strcat(roman, Roman[i][num / temp % 10]);
}
}