题目: https://leetcode.com/problems/roman-to-integer/
难度: Easy
思路:
integer to Roman 是 Medium,这个roman to integer是easy
所以用的傻方法,先特殊处理4,9,40,90,400,900,再加上剩下的数字
AC代码
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
lookup1 = {'CM':900,'CD':400,'XC':90,'XL':40,'IX':9,'IV':4}
lookup2 = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
num = 0
for i in lookup1.keys():
if i in s:
num += lookup1[i]
s = s.replace(i,'')
for char in s:
num += lookup2[char]
return num然后可以有更好的方法:
从前往后扫描,用一个临时变量记录分段数字。
如果当前比前一个大,说明这一段的值应当是这个值减去上一个值。比如IV = 5-1 =4; 否则,将当前值加入到结果中,然后开始下一段记录,比如VI = 5 + 1, II = 1 +1
所以这也就是罗马数字的基础,感觉?这样才不会读串?
AC代码
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
lookup = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
num = 0
for i in range(len(s)):
if i > 0 and lookup[s[i]] > lookup[s[i-1]]:
num += lookup[s[i]] - 2 * lookup[s[i-1]]
else:
num += lookup[s[i]]
return num