13. Roman to Integer | LeetCode Using Python
Check out the video below for a step-by-step guide and grab the Python code snippet to implement it yourself. Perfect for sharpening your skills and boosting your confidence in algorithmic thinking. Watch, learn, and code along with us!
Python code:
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman_to_integer = {
'I':1,
'V': 5,
'X': 10,
'L': 50,
'C' :100,
'D' : 500,
'M':1000,
}
#initialiaze output
output = 0
#iteration through s(string)
for i in range(len(s)):
#condtion
'''
Substraction: i < i+1; the number four is written as IV. Because the one is before the five we subtract it making four.
Addition: i >= i+1; 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
'''
if i + 1 < len(s) and roman_to_integer[s[i]] < roman_to_integer[s[i+1]]:
output -= roman_to_integer[s[i]]
#condition for addition and equals to
else:
output += roman_to_integer[s[i]]
#show output
return output