您的位置:首页 > 其它

Integer to Roman

2016-02-25 13:32 239 查看
首先是我自己看完网上的罗马数规则写的又臭又长的代码!(捂脸!!)

class Solution {
public:
string intToRoman(int num) {
string s="";
int a[4]={0},i=3;
while(num!=0)
{
a[i]=num%10;
num=num/10;
i--;
}
while(a[0]!=0)
{
s=s+'M';
a[0]--;
}
if(a[1]!=0)
{
if(a[1]==9) s=s+'C'+'M';
else if(a[1]>=5)
{
s=s+'D';
a[1]=a[1]-5;
while(a[1]!=0)
{
s=s+'C';
a[1]--;
}
}
else{
if(a[1]==4) s=s+'C'+'D';
else{ while(a[1]!=0)
{
s=s+'C';
a[1]--;
}
}
}
}
if(a[2]!=0)
{
if(a[2]==9) s=s+'X'+'C';
else if(a[2]>=5)
{
s=s+'L';
a[2]=a[2]-5;
while(a[2]!=0)
{
s=s+'X';
a[2]--;
}
}
else{
if(a[2]==4) s=s+'X'+'L';
else{  while(a[2]!=0)
{
s=s+'X';
a[2]--;
}
}
}
}
if(a[3]!=0)
{
if(a[3]==9) s=s+'I'+'X';
else if(a[3]>=5)
{
s=s+'V';
a[3]=a[3]-5;
while(a[3]!=0)
{
s=s+'I';
a[3]--;
}
}
else{
if(a[3]==4) s=s+'I'+'V';
else{ while(a[3]!=0)
{
s=s+'I';
a[3]--;
}
}
}
}
return s;
}
};


下面的是网上流传比较简单的:

public static String intToRoman(int num) {
String M[] = {"", "M", "MM", "MMM"};
String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: