python solution - easy to understand


  • 0
    L
    class Solution:
        def romanToInt(self, s):
            """
            :type s: str
            :rtype: int
            """
            
            i = len(s)-1
            summation = 0
            romanMap = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
            while i >=0 :
                currentDigit = s[i]
                if (i == 0):
                    summation += romanMap[s[i]]   
                else:
                    beforeDigit = s[i-1]
                    double = beforeDigit + currentDigit
                    if double in romanMap:
                        summation += romanMap[double]
                        i -= 1
                    else:
                        summation += romanMap[s[i]]
                i -= 1
            return summation
    

Log in to reply
 

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