说反了,是左小右大。而且这个总结也不准确,是以下具体三条规则: 1. I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten) 2. X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred) 3. C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)[5]
哈哈 翻了一下LC,原来我是hardcode的,应该更简洁一些 其实应该用一个index i的,我比较懒直接修改了原string,面试想修改原string的同 学最好征求面试官的意见 class Solution: # @param s, a string # @return an integer def romanToInt(self, s): ROMAN_INT = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1} result = 0 while s: if s[:2] in ROMAN_INT: result += ROMAN_INT[s[:2]] s = s[2:] elif s[:1] in ROMAN_INT: result += ROMAN_INT[s[:1]] s = s[1:] else: return -1 return result
than (a than
【在 A*******e 的大作中提到】 : 说反了,是左小右大。而且这个总结也不准确,是以下具体三条规则: : 1. I placed before V or X indicates one less, so four is IV (one less than : five) and nine is IX (one less than ten) : 2. X placed before L or C indicates ten less, so forty is XL (ten less than : fifty) and ninety is XC (ten less than a hundred) : 3. C placed before D or M indicates a hundred less, so four hundred is CD (a : hundred less than five hundred) and nine hundred is CM (a hundred less than : a thousand)[5]