Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution:
# @return an integer
def romanToInt(self, s):
numerals = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
sum=0
s=s[::-1]
last=None
for x in s:
if last and numerals[x]<last:
sum-=2*numerals[x]
sum+=numerals[x]
last=numerals[x]
return sum
本文介绍了一种将罗马数字转换为整数的方法。输入保证在1到3999范围内,通过定义罗马数字对应的整数值并逆序遍历字符串来实现转换。此算法能正确处理如IV(4)、IX(9)等特殊情况。
281

被折叠的 条评论
为什么被折叠?



