# Python solution with detailed explanation

• Solution

Roman to Integer https://leetcode.com/problems/roman-to-integer/

Algorithm

• You can build the algorithm easily by an example. XIV - go from X to V and simply add the value of character to result.
• One condition - if next character's lookup is more then previous, then subtraction must happen. Example: IV = 1 + 5 - 2 * 1 = 5 - 1 = 4
• http://www.tuomas.salste.net/doc/roman/numeri-romani-1-5000.html
``````class Solution(object):
def lookup(self, c):
if c == "I":
return 1
elif c == "V":
return 5
elif c == "X":
return 10
elif c == "L":
return 50
elif c == "C":
return 100
elif c == "D":
return 500
elif c == "M":
return 1000
else:
raise

def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for idx,c in enumerate(s):
result = result + self.lookup(c)
if idx>0 and self.lookup(s[idx-1]) < self.lookup(s[idx]):
result = result - 2*self.lookup(s[idx-1])
return result
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.