欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

整数转罗马数字 python

发布时间:2025/4/5 python 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 整数转罗马数字 python 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

原文链接

一个容易理解的方法
class Solution(object):def intToRoman(self, num):""":type num: int:rtype: str"""tmp = []roman = ''if not num:raise ValueErrorwhile num >= 1000:num -= 1000tmp.append('M')while num >= 900:num -= 900tmp.append('CM')while num >= 500:num -= 500tmp.append('D')while num >= 400:num -= 400tmp.append('CD')while num >= 100:num -= 100tmp.append('C')while num >= 90:num -= 90tmp.append('XC')while num >= 50:num -= 50tmp.append('L')while num >= 40:num -= 40tmp.append('XL')while num >= 10:num -= 10tmp.append('X')while num >= 9:num -= 9tmp.append('IX')while num >= 5:num -= 5tmp.append('V')while num >= 4:num -= 4tmp.append('IV')while num >= 1:num -= 1tmp.append('I')return roman.join(tmp) class Solution(object):def intToRoman(self, num):""":type num: int:rtype: str"""tmp = []hashmap = {'I': 1, 'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900, 'V': 5,'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}sort_hashmap = sorted(hashmap.items(), key=lambda _: _[1], reverse=True)roman = ''for i in range(len(sort_hashmap)):while num>=sort_hashmap[i][1]:num -= sort_hashmap[i][1]tmp.append(sort_hashmap[i][0])return roman.join(tmp)

总结

以上是生活随笔为你收集整理的整数转罗马数字 python的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。