题目描述
description.png思路:把所有字符相加,再单独把前一位比后一位小的拿出来,减去2倍差值即可。
先建立一个dict,然后n>0时相减
class Solution:
def romanToInt(self, s: str) -> int:
dict={'I':1,'V':5,'X':10,'L':50,
'C':100,'D':500,'M':1000,}
result = 0
for n in range(len(s)):
if n>0 and dict[s[n]] > dict[s[n-1]]:
result = result + dict[s[n]]-2*dict[s[n-1]]
else:
result = result + dict[s[n]]
return result
网友评论