Roman To Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Given a roman numeral, convert it to an integer.
(I can be placed before V and X to make 4 and 9. X can be placed before L and C to make 40 and 90. C can be placed before D and M to make 400 and 900.)
Python
####Forward Pointer (Runtime: 0ms, Memory: 12.3MB)
#DECLARE s: STRING
class Solution(object):
def romanToInt(self, s):
roman_map = {
"I": 1, "V": 5, "X": 10, "L": 50,
"C": 100, "D": 500, "M": 1000
}
total = 0
i = 0
while i < len(s)-1:
current = roman_map[s[i]]
following = roman_map[s[i+1]]
if current < following:
total -= current
else:
total += current
i += 1
total += roman_map[s[-1]]
return total
####Subtraction Method (Runtime: 5ms, Memory: 12.5MB)
#DECLARE s: STRING
class Solution(object):
def romanToInt(self, s):
roman_map = {
"I": 1, "V": 5, "X": 10, "L": 50,
"C": 100, "D": 500, "M": 1000
}
last = roman_map[s[0]]
total = last
for i in range(1, len(s)):
current = roman_map[s[i]]
if current > last:
total -= 2 * last
total += current
last = current
return total
####Dictionary Matching (Runtime: 8ms, Memory: 12.4MB)
#DECLARE s: STRING
class Solution(object):
def romanToInt(self, s):
roman_map = {
"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
}
total = 0
i = 0
while i < len(s):
if s[i:(i+2)] in roman_map:
total += roman_map[s[i:(i+2)]]
i += 2
else:
total += roman_map[s[i]]
i += 1
return total
Top comments (0)