# 题目链接

https://leetcode.com/problems/integer-to-roman/

# 解法

char * intToRoman(int num){
//3888为"MMMDCCCLXXXVIII",最多需要15个字符，但经过测试25个时无输出bug
char string[25];
char *str = string;
char *s = string;
while(num)
{
if(num>=1000)
{
*s++ = 'M';
num -= 1000;
}
else if(num>=900)
{
*s++ = 'C';
*s++ = 'M';
num -= 900;
}
else if(num>=500)
{
*s++ = 'D';
num -= 500;
}
else if(num>=400)
{
*s++ = 'C';
*s++ = 'D';
num -= 400;
}
else if(num>=100)
{
*s++ = 'C';
num -= 100;
}
else if(num>=90)
{
*s++ = 'X';
*s++ = 'C';
num -= 90;
}
else if(num>=50)
{
*s++ = 'L';
num -= 50;
}
else if(num>=40)
{
*s++ = 'X';
*s++ = 'L';
num -= 40;
}
else if(num>=10)
{
*s++ = 'X';
num -= 10;
}
else if(num>=9)
{
*s++ = 'I';
*s++ = 'X';
num -= 9;
}
else if(num>=5)
{
*s++ = 'V';
num -= 5;
}
else if(num>=4)
{
*s++ = 'I';
*s++ = 'V';
num -= 4;
}
else if(num>=1)
{
*s++ = 'I';
num -= 1;
}
}
*s = '\0';
return str;
}


# 测试代码

#include <stdio.h>
int main()
{
int num;
while(scanf("%d",&num)!= EOF)
{
printf("%s\n",intToRoman(num));
}
return 0;
}


# 遇到问题

1.为什么需要开长度为25的字符数组存储字符串，实测小于25时存在输出bug。（再经测试后...leetcode自带编译器中长度开25是可行的，dev c++中长度开到25也会有bug。保险起见开到肯定够用的100长度就不会出错了。）

# 小结

posted @ 2020-05-17 02:29  陳浴巾  阅读(146)  评论(0编辑  收藏  举报