Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:
将罗马字符保存到map中,观察罗马字符的规律,编写代码。
Python实现:
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
map = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 }
ans = 0
if len(s) == 1:
return map.get(s[0])
for i in range(len(s) - 1):
ch = map.get(s[i])
if (ch >= map.get(s[i+1])):
ans += ch
else:
ans -= ch
ans += map.get(s[-1]) # 加上最后一个数字
return ans
a = 'DCXXI'
b = Solution()
print(b.romanToInt(a)) # 621