代码略冗长。算法就是模拟,每次减一个5x,x是当前的位数,减到0为止。
public class Solution {
public String intToRoman(int num) {String rst="";
while(num>=1000)
{
rst+="M";
num-=1000;
}
//100
if(num>=900)
{
rst+="CM";
num-=900;
}
if(num>=500)
{
rst+="D";
while(num>=600)
{
rst+="C";
num-=100;
}
num-=500;
}
if(num>=400)
{
rst+="CD";
num-=400;
}
while(num>=100)
{
rst+="C";
num-=100;
}
//10
if(num>=90)
{
rst+="XC";
num-=90;
}
if(num>=50)
{
rst+="L";
while(num>=60)
{
rst+="X";
num-=10;
}
num-=50;
}
if(num>=40)
{
rst+="XL";
num-=40;
}
while(num>=10)
{
rst+="X";
num-=10;
}
//1
if(num==9)
{
rst+="IX";
num-=9;
}
if(num>=5)
{
rst+="V";
while(num>=6)
{
rst+="I";
num-=1;
}
num-=5;
}
if(num==4)
{
rst+="IV";
num-=4;
}
while(num>=1)
{
rst+="I";
num-=1;
}
return rst;
}
}
本文介绍了一种将整数转换为罗马数字的算法实现,通过循环减去特定数值并拼接相应的罗马数字字符,最终形成完整的罗马数字表示。
400

被折叠的 条评论
为什么被折叠?



