[Leet Code] Roman to Integer

Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.
Input: s = "III"
Output: 3
Input: s = "IV"
Output: 4
Input: s = "IX"
Output: 9
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
numerals = {"I":1, "IV":4,"V": 5,"IX":9,"X": 10,"XL":40,"L":50,"XC":90,"C":100,
"CD":400,"D":500,"CM":900,"M":1000}

running_total = 0
i = 0
while i < len(s):
if i+1 <= len(s) - 1:
if s[i]+s[i+1] in numerals:
running_total += numerals[s[i]+s[i+1]]
i+=2
else:
running_total += numerals[s[i]]
i+=1
else:
running_total += numerals[s[i]]
i+=1


return running_total

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store