题目描述
方法:
1. 从高位开始遍历减去
class Solution:
def intToRoman(self, num: int) -> str:
res = []
while num > 0:
if num >= 1000:
res.append("M")
num -= 1000
elif num >= 500:
if num >= 900:
res.append("CM")
num -= 900
else:
res.append("D")
num -= 500
elif num >= 100:
if num >= 400:
res.append("CD")
num -= 400
else:
res.append("C")
num -= 100
elif num >= 50:
if num >= 90:
res.append("XC")
num -= 90
else:
res.append("L")
num -= 50
elif num >= 10:
if num >= 40:
res.append("XL")
num -= 40
else:
res.append("X")
num -= 10
elif num >= 5:
if num >= 9:
res.append("IX")
num -= 9
else:
res.append("V")
num -= 5
elif num >= 1:
if num >= 4:
res.append("IV")
num -= 4
else:
res.append("I")
num -= 1
return "".join(res)
缺点: 代码太冗长
2. 利用哈希表优化代码,逻辑不变
class Solution:
def intToRoman(self, num: int) -> str:
res = []
roma = {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"}
for key in roma:
while num>=key:
num -= key
res.append(roma[key])
return "".join(res)