题目:整数转罗马数字
链接 https://leetcode.cn/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)
复杂度分析
时间复杂度:O(1)。由于valueSymbols 长度是固定的,且这 13 字符中的每个字符的出现次数均不会超过 3,因此循环次数有一个确定的上限。对于本题给出的数据范围,循环次数不会超过 15 次。
空间复杂度:O(1)。
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]
复杂度分析
时间复杂度:O(1)。计算量与输入数字的大小无关。
空间复杂度:O(1)。
class Solution:
def intToRoman(self, num: int) -> str:
# 使用哈希表,按照从大到小顺序排列
hashmap = {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'}
res = ''
for key in hashmap:
if num // key != 0:
count = num // key # 比如输入4000,count 为 4
res += hashmap[key] * count
num %= key
return res
作者:z1m
链接:https://leetcode.cn/problems/integer-to-roman/solution/tan-xin-ha-xi-biao-tu-jie-by-ml-zimingmeng/