Roman to Integer (Leetcode 13)

Problem Link: https://leetcode.com/problems/roman-to-integer/

class Solution:
    def romanToInt(self, s: str) -> int:
        
        ans=0
        d={}
        d['I']=1
        d['V']=5
        d['X']=10
        d['L']=50
        d['C']=100
        d['D']=500
        d['M']=1000
        n=len(s)
        i=n-1
        while(i-1>=0):
            if(d[s[i]]>d[s[i-1]]):
                ans=ans+d[s[i]]
                ans=ans-d[s[i-1]]
                i=i-2
            elif(d[s[i]]<=d[s[i-1]]):
                ans=ans+d[s[i]]
                i=i-1
        if(i==0):
            ans=ans+d[s[i]]
        return ans

Last updated