Python实现罗马数字转阿拉伯数字
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
s = list(s)
sum = 0
convert = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
for i in range(len(s)-1):
while (convert[s[i]] < convert[s[i + 1]]):
if s[i] == 'I' and s[i + 1] == 'V':
sum -= convert[s[i]]
break
elif s[i] == 'I' and s[i + 1] == 'X':
sum -= convert[s[i]]
break
elif s[i] == 'X' and s[i + 1] == 'L':
sum -= convert[s[i]]
break
elif s[i] == 'X' and s[i + 1] == 'C':
sum -= convert[s[i]]
break
elif s[i] == 'C' and s[i + 1] == 'D':
sum -= convert[s[i]]
break
elif s[i] == 'C' and s[i + 1] == 'M':
sum -= convert[s[i]]
break
else:
sum += convert[s[i]]
break
i += 1
sum += convert[s[-1]]
return sum
st = 'IVCD'
p = Solution()
print(p.romanToInt(st))
输出:404