文章目录
leetcode12:12. 整数转罗马数字
题目描述
罗马数字包含以下七种字符: I
, V
, X
, L
,C
,D
和 M
I
1V
5X
10L
50C
100D
500M
1000
Example
输入: 58
输出: "LVIII"
解释: L = 50, V = 5, III = 3
solution idea
暴力搜索
class Solution {
public:
/*
** 暴力搜索
*/
string intToRoman(int num)
{
string result;
vector<string> tmpVec1 = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
vector<string> tmpVec2 = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
vector<string> tmpVec3 = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
vector<string> tmpVec4 = {"", "M", "MM", "MMM"};
vector<vector<string>> store = {tmpVec1, tmpVec2, tmpVec3, tmpVec4};
result.append(store[3][num / 1000 % 10]); //千位
result.append(store[2][num / 100 % 10]); //百位
result.append(store[1][num / 10 % 10]); //十位
result.append(store[0][num % 10]); //个位
return result;
}
};
贪心法
class Solution {
public:
/*
** 贪心法
*/
string intToRoman(int num)
{
string result;
vector<int> intGroup={1,4,5,9,10,40,50,90,100,400,500,900,1000};
vector<string> strGroup={"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
while(num)
{
for(int i=intGroup.size()-1;i>=0;i--)
{
if (num>=intGroup[i])
{
result.append(strGroup[i]);
num-=intGroup[i];
break;
}
}
}
return result;
}
};
参考文献
- c++ prime 第5版
来源:CSDN
作者:三生石gg
链接:https://blog.csdn.net/qq_41918762/article/details/104109497