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