题目描述
罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。
字符 数值
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。
通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:
I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。
X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。
C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。
给你一个整数,将其转为罗马数字。
我的题解
- 思路
考虑所有情况(特殊+正常),逐个做除法、减法运算直到num=0。
- show me the code
char * intToRoman(int num){
char *arr[] = {"IV", "IX", "XL", "XC", "CD", "CM"};
// 动态分配内存
char *res = (char *)malloc(sizeof(char)* 50);
// 不要忘记结束符
res[0] = '\0';
if(num <= 0){
return res;
}
while(num>0){
if(num/1000 > 0){
int size = num / 1000;
while(size > 0){
strcat(res, "M");
// res += "M";
size--;
}
num %= 1000;
}else if(num/900 > 0){
int size = num / 900;
while(size > 0){
strcat(res, "CM");
// res += "CM";
size--;
}
num %= 900;
}else if(num/500 > 0){
int size = num / 500;
while(size > 0){
strcat(res, "D");
// res += "D";
size--;
}
num %= 500;
}else if(num/400 > 0){
int size = num / 400;
while(size > 0){
strcat(res, "CD");
// res += "CD";
size--;
}
num %= 400;
}else if(num/100 > 0){
int size = num / 100;
while(size > 0){
strcat(res, "C");
// res += "C";
size--;
}
num %= 100;
}else if(num/90 > 0){
int size = num / 90;
while(size > 0){
strcat(res, "XC");
// res += "XC";
size--;
}
num %= 90;
}else if(num/50 > 0){
int size = num / 50;
while(size > 0){
strcat(res, "L");
// res += "L";
size--;
}
num %= 50;
}else if(num/40 > 0){
int size = num / 40;
while(size > 0){
strcat(res, "XL");
// res += "XL";
size--;
}
num %= 40;
}else if(num/10 > 0){
int size = num / 10;
while(size > 0){
strcat(res, "X");
// res += "X";
size--;
}
num %= 10;
}else if(num/9 > 0){
int size = num / 9;
while(size > 0){
strcat(res, "IX");
// res += "IX";
size--;
}
num %= 9;
}else if(num/5 > 0){
int size = num / 5;
while(size > 0){
strcat(res, "V");
// res += "V";
size--;
}
num %= 5;
}else if(num/4 > 0){
int size = num / 4;
while(size > 0){
strcat(res, "IV");
// res += "IV";
size--;
}
num %= 4;
}else {
switch(num){
case 3:
strcat(res, "III");
// res += "III";
num -= 3;
break;
case 2:
strcat(res, "II");
// res += "II";
num -= 2;
break;
case 1:
strcat(res, "I");
// res += "I";
num -= 1;
break;
case 0:
break;
}
}
}
return res;
}
执行结果:
原题链接:https://leetcode-cn.com/problems/integer-to-roman