class Solution:
def intToRoman(self, num: int) -> str:
romanNum = ["I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"]
numeral = [1,4,5,9,10,40,50,90,100,400,500,900,1000]
if num < 1 or num > 3999:
return 0
res, i = "", len(romanNum) -1
while num > 0:
if num - numeral[i] >= 0:
res += romanNum[i]
num -= numeral[i]
else:
i -= 1
return res
同样的运行速度,另一种描述方式:
class Solution:
def intToRoman(self, num: int) -> str:
romanNum = ["I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"]
numeral = [1,4,5,9,10,40,50,90,100,400,500,900,1000]
if num < 1 or num > 3999:
return 0
res = ""
for i in list(range(len(romanNum)))[::-1]:
while numeral[i] <= num:
res += romanNum[i]
num -= numeral[i]
return res