Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
羅馬數字記數方法:
基本字符 I V X L C D M
相應的阿拉伯數字表示為 1 5 10 50 100 500 1000
相同的數字連寫、所表示的數等于這些數字相加得到的數、如:Ⅲ=3;
小的數字在大的數字的右邊、所表示的數等于這些數字相加得到的數、 如:Ⅷ=8、Ⅻ=12;
小的數字、(限于 Ⅰ、X 和 C)在大的數字的左邊、所表示的數等于大數減小數得到的數、如:Ⅳ=4、Ⅸ=9;
正常使用時、連寫的數字重復不得超過三次;
在一個數的上面畫一條橫線、表示這個數擴大 1000 倍。
組數規則
基本數字 Ⅰ、X 、C 中的任何一個、自身連用構成數目、或者放在大數的右邊連用構成數目、都不能超過三個;放在大數的左邊只能用一個;
不能把基本數字 V 、L 、D 中的任何一個作為小數放在大數的左邊采用相減的方法構成數目;放在大數的右邊采用相加的方式構成數目、只能使用一個;
分析
將一個整數轉化為羅馬數字。因此可以通過數位上的數字挨個解析,之后組成為答案。
也可以依次減去{1000,900,500,400,100,90,50,40,10,9,5,4,1},組成最后的答案。
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 * ans=(char *)malloc(sizeof(char)*50);
int length=0,i=0;
int temp=num/1000%10;
while(c[3][temp][i]!='\0')
{
ans[length]=c[3][temp][i];
length++;
i++;
}
i=0;
temp=num/100%10;
while(c[2][temp][i]!='\0')
{
ans[length]=c[2][temp][i];
length++;
i++;
}
i=0;
temp=num/10%10;
while(c[1][temp][i]!='\0')
{
ans[length]=c[1][temp][i];
length++;
i++;
}
i=0;
temp=num%10;
while(c[0][temp][i]!='\0')
{
ans[length]=c[0][temp][i];
length++;
i++;
}
ans[length]='\0';
return ans;
}