首先建立一个数组,保持1 到3999的罗马数,以一位单位(0,1,2,3,4,5,6,7,8,9),
10为单位(0,10,20,30,40,50,60,70,80,90)
100为单位(0,100,200,300,400,500,600,700,800,900)
1000为单位(0,1000,2000,3000)
num/1000为index从(0,1000,2000,3000)找
num/100%10 从(0,100,200,300,400,500,600,700,800,900)
num/10%10 从(0,10,20,30,40,50,60,70,80,90)
num%10 从(0,1,2,3,4,5,6,7,8,9)找
char* intToRoman(int num) {
char *result = (char*)malloc(sizeof(char)*100);
char one[][5] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
char two[][5] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
char three[][5] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
char four[][5] = {"", "M", "MM", "MMM"};
result[0] = '\0';
strcat(result, four[num/1000]);
//num %= 1000;
strcat(result, three[num/100%10]);
//num %= 100;
strcat(result, two[num/10%10]);
//num %= 10;
strcat(result, one[num%10]);
return result;
}
网友评论