整数转罗马数字(贪心, C++和python)
程序员文章站
2022-05-09 18:01:53
12. 整数转罗马数字题目链接这道题力扣题解上面给出了很多解法,贪心是目前逻辑最简单且效率高的。先把最大值1000替换,替换完成再替换900,以此类推……C++:class Solution {public: string intToRoman(int num) { vector key = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector
12. 整数转罗马数字
题目链接
这道题力扣题解上面给出了很多解法,贪心是目前逻辑最简单且效率高的。
先把最大值1000替换,替换完成再替换900,以此类推……
C++:
class Solution {
public:
string intToRoman(int num) {
vector<int> key = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
vector<string> value = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string ans = "";
for(int i = 0; i < 13; i++)
{
while(num >= key[i])
{
ans += value[i];
num-=key[i];
}
}
return ans;
}
};
python:
class Solution:
def intToRoman(self, num: int) -> str:
key = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
value = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
ans = ""
for i in range(0, 13):
while num >= key[i]:
ans += value[i]
num -= key[i]
return ans
如果对你有帮助的话,请点个赞哦!
本文地址:https://blog.csdn.net/qq_41946404/article/details/109952822