Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
关于罗马数字的详细表示:罗马数字详解
但是并没有链接中表示的那么复杂,罗马数字只有1,5,10,50,100,500,1000(I,V,X,L,C,D,M)这几个数字,因此,我们可以从大到小遍历,比如2345,2000>1000,得到一个’M’,然后变成1345,同样,再减1000,得到”MM”,变成345,依次类推即可。
但是对于4,9,40,90,900表示的时候并不是符合规律的表示,其分别为IV,IX,XL,XC等等……
然后再参照是航母的,大于1000时,我们减去1000,并得到一个M以此类推,就能得到想要的结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void IntegerToRoman(int n);
int main()
{
int n;
while(scanf("%d",&n) == 1){
IntegerToRoman(n);
}
return 0;
}
void IntegerToRoman(int n)
{
if(n < 1 || n > 3999)
return;
int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
char *roman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
char store[20] = {0};
int len = sizeof(value)/sizeof(int);
for(int i = 0;i < len;++i){
while(n >= value[i]){
n -= value[i];
strcat(store,roman[i]);
}
}
printf("%s\n",store);
}