Problem:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:
方法与LeetCode 12题同理。
Solution:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
returnint = 0
slen = len(s)
i = 0
while i < slen:
if s[i] == 'M':
returnint += 1000
i += 1
elif s[i] == 'C' and i + 1 != slen and s[i+1] == 'M':
returnint += 900
i += 2
elif s[i] == 'D':
returnint += 500
i += 1
elif s[i] == 'C' and i + 1 != slen and s[i+1] == 'D':
returnint += 400
i += 2
elif s[i] == 'C':
returnint += 100
i += 1
elif s[i] == 'X' and i + 1 != slen and s[i+1] == 'L':
returnint += 40
i += 2
elif s[i] == 'X' and i + 1 != slen and s[i+1] == 'C':
returnint += 90
i += 2
elif s[i] == 'X':
returnint += 10
i += 1
elif s[i] == 'L':
returnint += 50
i += 1
elif s[i] == 'I' and i + 1 != slen and s[i+1] == 'X':
returnint += 9
i += 2
elif s[i] == 'I' and i + 1 != slen and s[i+1] == 'V':
returnint += 4
i += 2
elif s[i] == 'V':
returnint += 5
i += 1
elif s[i] == 'I':
returnint += 1
i += 1
return returnint

本文介绍了一种将罗马数字转换为整数的方法。通过解析罗马数字的构成规则,设计了一个迭代算法来逐步读取每个字符并累加相应的数值。该算法能够正确处理包括特殊组合在内的各种常见罗马数字。
642

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



