Skip to content

Instantly share code, notes, and snippets.

@rdtr
Created January 5, 2016 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rdtr/7ad382e7ab15a92442d3 to your computer and use it in GitHub Desktop.
Save rdtr/7ad382e7ab15a92442d3 to your computer and use it in GitHub Desktop.
algorithm_math_romanr_to_integer.py
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
leng = len(s)
s = s + ' '
i = 0
res = 0
while i < leng:
ch, nxCh = s[i], s[i+1]
inc = 1
if ch == 'M':
res += 1000
elif ch == 'C':
if nxCh == 'M':
res += 900
inc = 2
elif nxCh == 'D':
res += 400
inc = 2
else:
res += 100
elif ch == 'D':
res += 500
elif ch == 'X':
if nxCh == 'C':
res += 90
inc = 2
elif nxCh == 'L':
res += 40
inc = 2
else:
res += 10
elif ch == 'L':
res += 50
elif ch == 'I':
if nxCh == 'X':
res += 9
inc = 2
elif nxCh == 'V':
res += 4
inc = 2
else:
res += 1
else: # if ch == 'V'
res += 5;
i += inc
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment