Roman to Integers:Easy to understand


  • 0
    K

    class Solution:
    def romanToInt(self, s):
    """
    :type s: str
    :rtype: int
    """
    d=dict()
    d['I']=1
    d['V']=5
    d['X']=10
    d['L']=50
    d['C']=100
    d['D']=500
    d['M']=1000
    res=d[s[-1]]#assigning value of last roman letter to res
    for i in range(len(s)-2,-1,-1):#traversing from right to left i.e len-2 to 0
    if(d[s[i]]<d[s[i+1]]):#comparing those two values
    res-=d[s[i]]#when smaller it gets subtracted
    else:
    res+=d[s[i]]#else it gets added
    return res


Log in to reply
 

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