Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
方法
將羅馬數字和數字的對應關系從大到小列舉出來,注意900、400、90、40、9、4這些數字對應的羅馬字符
c代碼
#include <assert.h>
#include <stdlib.h>
#include <string.h>
char* intToRoman(int num) {
int vals[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
char* strs[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
char* roman = (char *)malloc(sizeof(char) * 100);
int i = 0;
int length = sizeof(vals)/sizeof(int);
for(i = 0; i < length; i++) {
while(num >= vals[i]) {
strcat(roman, strs[i]);
num -= vals[i];
}
}
return roman;
}
int main() {
assert(strcmp(intToRoman(9), "IX") == 0);
return 0;
}