您的位置:首页 > 其它

leetcode之路012 Integer to Roman

2015-07-28 20:56 302 查看
题目大意:将整数转化为罗马形式表示,输入为1-3999。对照表:

基本字符I
V
X
L
C
D
M
相应的阿拉伯数字表示为1
5
10
50
100
500
1000

思路:

1、用map记录对照表,对输入字符进行查找对应值。

2、依次处理每一位,从最低位开始。对于每一位j,分5种情况,j=9,5<j<9,j=5,j=4,0<j<4,每一个处理是独立的,判断后添加相应字符到结果字符串resu中即可。

下面是ac的代码,时间为56ms:

class Solution {
public:
string intToRoman(int num) {
string resu;
int i=10,j,k;
int te1,te2;
unordered_map<int,char> map;
map[1]='I';map[5]='V';map[10]='X';map[50]='L';
map[100]='C';map[500]='D';map[1000]='M';
while(num*10>=i)
{
j=(num%i)/(i/10);
if(j==9)
{
te1=1;te2=10;
resu.push_back(map[te2*i/10]);
resu.push_back(map[te1*i/10]);
}
else if(j>5)
{
te1=5;te2=1;
for(k=0;k<j-5;++k)
resu.push_back(map[te2*i/10]);
resu.push_back(map[te1*i/10]);
}
else if(j==5)
resu.push_back(map[5*i/10]);
else if(j==4)
{
resu.push_back(map[5*i/10]);
resu.push_back(map[1*i/10]);
}
else if(j>0)
{
for(k=0;k<j;++k)
resu.push_back(map[1*i/10]);
}
i*=10;
}
reverse(resu.begin(),resu.end());
return resu;
}
};


下面是改进的代码,减少了运算,运行为52ms,如下:
class Solution {
public:
string intToRoman(int num) {
string resu;
int i=1,j,k;
unordered_map<int,char> map;
map[1]='I';map[5]='V';map[10]='X';map[50]='L';
map[100]='C';map[500]='D';map[1000]='M';
while(num)
{
j=num%10;
if(j>5&&j<9)
{
for(k=0;k<j-5;++k)
resu.push_back(map[1*i]);
resu.push_back(map[5*i]);
}
else if(j>0&&j<4)
{
for(k=0;k<j;++k)
resu.push_back(map[1*i]);
}
else if(j==9)
{
resu.push_back(map[10*i]);
resu.push_back(map[1*i]);
}
else if(j==5)
resu.push_back(map[5*i]);
else if(j==4)
{
resu.push_back(map[5*i]);
resu.push_back(map[1*i]);
}
i*=10;
num=num/10;
}
reverse(resu.begin(),resu.end());
return resu;
}
};


讨论区比较简单的实现都是基于制定规则,用表来表示各种情况,进行查找得到值,如下:

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