# My Straightforward Python Solution

• ``````class Solution:
# @param {string} s
# @return {integer}
def romanToInt(self, s):
roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i+1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
``````

*Note: The trick is that the last letter is always added. Except the last one, if one letter is less than its latter one, this letter is subtracted.

• Smart solution, but how did you find it?

• Last digit in roman number will always perform add operation.

• @wenfengqiu I use the [i:j] operators to beat the corner cases in python:

``````def romanToInt(self, s):
roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
res, i = 0, 0
for i in range(len(s)):
curr, nxt = s[i], s[i+1:i+2]
if nxt and roman[curr] < roman[nxt]:
res -= roman[curr]
else:
res += roman[curr]
return res``````

• This post is deleted!

• @wenfengqiu

Does iiv a legal expression ? If so, then this solution does not look like can calculate iiV, ( can be iii)
1st i is equal or larger than second i then add
but 3rd is subtract

so output for this one is 4 not 3

• @alexliubj
IIV is NOT legal. What you are getting at is probably III.

• Same my idea: using dictionary and travel backward:

``````def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
_dict = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
prev = 0
sum = 0
for i in s[::-1]:
curr = _dict[i]
if prev > curr:
sum -= curr
else:
sum += curr
prev = curr
return sum
``````

• class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
I(1)，V(5)，X(10)，L(50)，C(100)，D(500)，M(1000)
"""
r_sum = 0
temp = 0
rul = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for ch in s:
ch_val = int(rul[ch])
r_sum = r_sum + ch_val
if temp < ch_val:
r_sum -= temp*2
temp = ch_val
return r_sum

• ``````class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
I(1)，V(5)，X(10)，L(50)，C(100)，D(500)，M(1000)
"""
r_sum = 0
temp = 0
rul = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for ch in s:
ch_val = int(rul[ch])
r_sum  = r_sum + ch_val
if temp < ch_val:
r_sum -= temp*2
temp = ch_val
return r_sum
``````

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