Python3:
class Solution:
def intToRoman(self, num: int) -> str:
# 初始化字典
val={
1000:"M",
900:"CM",
500:"D",
400:"CD",
100:"C",
90:"XC",
50:"L",
40:"XL",
10:"X",
9:"IX",
5:"V",
4:"IV",
1:"I"
}
# 存储结果
ans=""
# 遍历字典
for key,value in val.items():
while key<=num:
ans+=value
num-=key
# 返回结果
return ans
C++:
// 初始化pair结构
const pair<int,string> val[]={
{1000,"M"},
{900,"CM"},
{500,"D"},
{400,"CD"},
{100,"C"},
{90,"XC"},
{50,"L"},
{40,"XL"},
{10,"X"},
{9,"IX"},
{5,"V"},
{4,"IV"},
{1,"I"}
};
class Solution {
public:
string intToRoman(int num) {
// 存储结果
string ans="";
// 遍历pair结构的val
for(const auto va :val){
// 从大到小存储输出
while(va.first<=num){
ans+=va.second;
num-=va.first;
}
}
// 返回结果
return ans;
}
};
标签:va,存储,val,int,罗马数字,整数,intToRoman,leetcode12,pair
From: https://blog.csdn.net/qq_61319288/article/details/144912702