LeetCode solutions

13. Roman to Integer

My accepted Python solution to LeetCode problem 13, Roman to Integer, running in 3ms.

  • Difficulty: Easy
  • Python
  • Runtime 3ms
  • Memory 17.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 3ms, memory 17.3MB, accepted 2025-12-29.

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

Source