← switch

13. Roman to Integer

easy

Hash Table · Math · String

read the problem on leetcode →

first solved 15 Aug 2024 · 2 accepted submissions

python
class Solution:
    def romanToInt(self, s: str) -> int:
        values = {
            "I": 1,"V": 5,"X": 10,"L": 50,"C": 100,"D": 500,"M": 1000}

        total = 0

        for i in range(len(s)):
            if i + 1 < len(s) and values[s[i]] < values[s[i + 1]]:
                total -= values[s[i]]
            else:
                total += values[s[i]]

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