Hide sidebar

Roman to Integer

MathString
EasyLeetCode #13
15 min

Problem Statement

Given a roman numeral, convert it to an integer.

Example

Example 1:

Input: s = "LVIII"

LVIII58

Output: 58

Explanation: L = 50, V = 5, III = 3.

Solution (Left-to-Right Pass)

A simple and effective way to convert a Roman numeral to an integer is to process the string from left to right. The key is to handle the cases where a smaller value precedes a larger one (like IV for 4 or IX for 9).

Algorithm Steps

  • Create a map to store the integer values of each Roman symbol.
  • Initialize a result variable to 0.
  • Iterate through the Roman numeral string from left to right.
  • For each symbol, check if the next symbol has a larger value.
  • If it does, subtract the current symbol's value from the result.
  • Otherwise, add the current symbol's value to the result.
  • After the loop, the result will hold the final integer value.
L
V
I
I
I

Result: 0

Start with Roman numeral "LVIII" and a result of 0.
Roman to Integer Solution

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