leetcode-12.整数转罗马数字
这题对我有点反直觉。
首先应该把特殊规则构建出要添加的字符,,即把4、9、40、90这些要编成什么字符显式定义出来, 否则靠程序判别,会很麻烦,需要知道首位数字才行,莫不如把规则全写明白。
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
res += hashmap[key] * count
num %= key
return res