系列索引:菜菜的刷题日记 | 被LeetCode用Python狂虐的那段日子
菜鸡的刷题之路——2022/1/24,这几天忙着肝并发编程,题在做但是没空写题解,今晚补一篇。
文章目录
- 【题目】
- 【官方思路】
- 【我的代码】
- 【思考】
题目链接:https://leetcode-cn.com/problems/integer-to-roman/
class Solution:
VALUE_SYMBOLS = [
(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"),
]
def intToRoman(self, num: int) -> str:
roman = list()
for value, symbol in Solution.VALUE_SYMBOLS:
while num >= value:
num -= value
roman.append(symbol)
if num == 0:
break
return "".join(roman)
class Solution:
THOUSANDS = ["", "M", "MM", "MMM"]
HUNDREDS = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
TENS = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"]
ONES = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"]
def intToRoman(self, num: int) -> str:
return Solution.THOUSANDS[num // 1000] + \
Solution.HUNDREDS[num % 1000 // 100] + \
Solution.TENS[num % 100 // 10] + \
Solution.ONES[num % 10]
主要使用了字典的遍历,代码比较简洁易懂,但是效率不高,仅供参考~
class Solution:
def intToRoman(self, num: int) -> str:
value = {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'}
strs = ""
for key, val in value.items():
while num >= key:
num -= key
strs += val
return strs
早睡早起是我遥不可及的梦
Python力扣题解系列持续更新,欢迎
点赞收藏
+关注
上一篇:菜菜的刷题日记 | 9. 回文数
下一篇:菜菜的刷题日记 | 20.有效的括号(B站笔试题)
本人水平有限,文章中不足之处欢迎下方评论区批评指正~如果感觉对你有帮助,点个赞 支持一下吧 ~
不定期分享 有趣、有料、有营养内容,欢迎 订阅关注 我的博客 ,期待在这与你相遇 ~