classSolution(object): defintToRoman(self, num): """ :type num: int :rtype: str """ result = '' nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1] chars = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] for i in nums: x = num // i num = num % i result += x*chars[nums.index(i)] return result
这样当然是没问题得,但是我看到评论区居然有人用python的字典也成功了
这就很疑惑了,于是我修改了代码:
classSolution(object): defintToRoman(self, num): """ :type num: int :rtype: str """ result = "" roman = {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 i in roman: x = num // i num = num % i result += x*roman[i] return result
classSolution: defromanToInt(self, s: str) -> int: d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000} result = 0 for i,n in enumerate(s): a = max(i-1,0) b = d.get(s[a:i+1], d[n]) # 每次取两个元素,如果有就说明是4,9这类,如果没有就采取默认的 d[n] result += b return result
不得不说这种方法确实很巧妙,甚至可以浓缩为一句话
return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))