13. Roman to Integer - LeetCode Solution


Math String

Python Code:

class Solution:
    def romanToInt(self, s: str) -> int:
        
        l = {"I" : 1, "V" :5, "X" : 10, "L" : 50, "C": 100, "D": 500, "M": 1000}
        ans = 0
        flag = 0
        for i in range(len(s) - 1, 0, -1):
            if flag == 1:
                flag = 0
                continue
            
                
            if l[s[i]] > l[s[i-1]]:
                flag = 1
                ans+= l[s[i]] - l[s[i-1]]
            else:
                ans += l[s[i]]
                
        if flag == 0:
            ans+= l[s[0]]
        return ans
                
                
                


Comments

Submit
0 Comments
More Questions

1714E - Add Modulo 10
1714A - Everyone Loves to Sleep
764A - Taymyr is calling you
1714B - Remove Prefix
1264F - Beautiful Fibonacci Problem
52A - 123-sequence
1543A - Exciting Bets
1714D - Color with Occurrences
215B - Olympic Medal
1445A - Array Rearrangment
1351A - A+B (Trial Problem)
935B - Fafa and the Gates
1291A - Even But Not Even
1269A - Equation
441A - Valera and Antique Items
1702C - Train and Queries
816B - Karen and Coffee
838D - Airplane Arrangements
148B - Escape
847G - University Classes
1110A - Parity
1215B - The Number of Products
604C - Alternative Thinking
1204C - Anna Svyatoslav and Maps
322A - Ciel and Dancing
1689B - Mystic Permutation
1711B - Party
1702D - Not a Cheap String
1714F - Build a Tree and That Is It
1703F - Yet Another Problem About Pairs Satisfying an Inequality