您的位置:首页 > 其它

Integer to Roman

2015-07-25 14:42 225 查看


Integer to Roman

Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
备注:只要弄明白roman numeral, 这个题不算难,自己出现的
主要问题是在命名方面,注意:尽量少使用无法定义含义的名称,因为
后面很容易出现变量复用(i,j,k之类),这类的隐形错误使结果不正确,却又
难以发现原因。
class Solution {
public:
string intToRoman(int num) {
int len = 1000;
string s = "";
int n = num/len;
int i ;
for(i = 0;i< n;++i)
s = s+"M";
num =  num - n*len;
len/=10;
n = num/len;
i = 0;
string str[] = {"CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
while(true)
{
if(n > 0)
{
if(9 == n)
s = s+str[i];
else if(4 == n)
s = s+str[i+2];
else if(n >0 && n <4)
{
for(int k = 0;k < n;++k)
s = s+str[i+3];
}
else if(n > 4 && n < 9)
{
int j = n-5;
if(j == 0)
s = s+str[i+1];
else
{
s = s+str[i+1];
while(j > 0)
{
s = s+str[i+3];
--j;
}
}
}
}
i = i+4;
if(i > 11)break;
num = num-n*len;
len/=10;
if(len > 0)
n = num/len;
}
return s;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: