Roman to Integer
Description:
Given a roman numeral, convert it to an integer.
The answer is guaranteed to be within the range from 1 to 3999.
Example
IV -> 4
XII -> 12
XXI -> 21
XCIX -> 99
Clarification
What is Roman Numeral?
https://en.wikipedia.org/wiki/Roman_numerals
https://zh.wikipedia.org/wiki/罗马数字
http://baike.baidu.com/view/42061.htm
Code:
class Solution:
"""
@param s: Roman representation
@return: an integer
"""
def romanToInt(self, s):
# write your code here
digits = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
res = 0
pre = 1
for i in range(len(s)-1, -1, -1):
if digits[s[i]]>=pre:
pre = digits[s[i]]
res += digits[s[i]]
else:
res -= digits[s[i]]
return res