leetcode题库 第12题 整数转罗马数字
难度:中等
C代码
char * intToRoman(int num){
char *roman;
roman = (char *)malloc(50);
int i = 0;
while(num>=1000) { num -= 1000; roman[i++] = 'M'; }
int count = 0;
while(num>=100)
{
num -= 100;
roman[i++] = 'C';
count ++;
}
if(count == 4 ) { i = i-3; roman[i++] = 'D'; }
if(count == 5 ) { i = i -5; roman[i++] = 'D'; }
if(count >=6 && count <=8) { i = i -count; roman[i++] = 'D'; i = i+count -5; }
if(count == 9 ) { i = i - 9; roman[i++] = 'C'; roman[i++] = 'M'; }
count = 0;
while(num>=10)
{
num -= 10;
roman[i++] = 'X';
count ++;
}
if(count == 4 ) { i = i-3; roman[i++] = 'L'; }
if(count == 5 ) { i = i -5; roman[i++] = 'L'; }
if(count >=6 && count <=8) { i = i -count; roman[i++] = 'L'; i = i+count -5; }
if(count == 9 ) { i = i - 9; roman[i++] = 'X'; roman[i++] = 'C'; }
count = 0;
while(num>=1)
{
num -= 1;
roman[i++] = 'I';
count ++;
}
if(count == 4 ) { i = i-3; roman[i++] = 'V'; }
if(count == 5 ) { i = i -5; roman[i++] = 'V'; }
if(count >=6 && count <=8) { i = i -count; roman[i++] = 'V'; i = i+count -5; }
if(count == 9 ) { i = i - 9; roman[i++] = 'I'; roman[i++] = 'X'; }
roman[i]='\0';
return roman;
}