1、自己的想法,存储部分表达方式,直接拿过来用
1-10,10-100,100-1000,1000-3000
class Solution:
def intToRoman(self, num: int) -> str:
stor1=['I','II','III','IV','V','VI','VII','VIII','IX','X']
stor2=['X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C']
stor3=['C','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
stor4=['M','MM','MMM']
result=[]
while(num > 0):
if(num >= 1000):
ind = num//1000
result.append(stor4[ind-1])
num = num % 1000
elif(num >= 100):
ind = num//100
result.append(stor3[ind-1])
num = num % 100
elif(num >= 10):
ind = num//10
result.append(stor2[ind-1])
num = num % 10
else:
result.append(stor1[num-1])
num = 0
return "".join(result)
优化:
class Solution:
def intToRoman(self, num: int) -> str:
stor1=['','I','II','III','IV','V','VI','VII','VIII','IX','X']
stor2=['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC','C']
stor3=['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM','M']
stor4=['','M','MM','MMM']
result = stor4[num//1000] + stor3[(num%1000)//100] + stor2[(num%100)//10] + stor1[num%10]
return result
2、官方的贪心算法
由大到小进行排查,顺便学习一下代码
class Solution:
def intToRoman(self, num: int) -> str:
# List中为元组
NumSymbols=[(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")]
result=[]
# 取出元组的内容
for value, symbol in NumSymbols:
if(num == 0):
break
# divmod() 把除数和余数运算结果结合起来 count=num//value num=num%value
count, num = divmod(num, value)
result.append(symbol*count)
return "".join(result)