Roman to Integer in Python

Converting Roman numerals to integers is a common programming problem. Roman numerals use specific symbols with defined values, and some combinations follow subtraction rules.

Roman Numeral Values

The basic Roman numeral symbols and their integer values are ?

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

Subtraction Rules

Some Roman numerals use subtraction instead of addition ?

  • I can be placed before V (5) and X (10) to make 4 and 9
  • X can be placed before L (50) and C (100) to make 40 and 90
  • C can be placed before D (500) and M (1000) to make 400 and 900

Method 1: Dictionary Lookup Approach

This method uses a dictionary containing both single symbols and two-character combinations ?

def roman_to_int(roman_str):
    """Convert Roman numeral to integer using dictionary lookup"""
    roman_values = {
        'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,
        'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900
    }
    
    i = 0
    total = 0
    
    while i < len(roman_str):
        # Check for two-character combinations first
        if i + 1 < len(roman_str) and roman_str[i:i+2] in roman_values:
            total += roman_values[roman_str[i:i+2]]
            i += 2
        else:
            total += roman_values[roman_str[i]]
            i += 1
    
    return total

# Test examples
print(roman_to_int("III"))      # 3
print(roman_to_int("CDXLIII"))  # 443
print(roman_to_int("MCMXC"))    # 1990
3
443
1990

Method 2: Left-to-Right Comparison

This approach compares each character with the next one to determine addition or subtraction ?

def roman_to_int_comparison(roman_str):
    """Convert Roman numeral using left-to-right comparison"""
    roman_values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    
    total = 0
    
    for i in range(len(roman_str)):
        # If current value is less than next value, subtract it
        if i + 1 < len(roman_str) and roman_values[roman_str[i]] < roman_values[roman_str[i + 1]]:
            total -= roman_values[roman_str[i]]
        else:
            total += roman_values[roman_str[i]]
    
    return total

# Test examples
print(roman_to_int_comparison("IV"))     # 4
print(roman_to_int_comparison("IX"))     # 9
print(roman_to_int_comparison("XL"))     # 40
print(roman_to_int_comparison("CD"))     # 400
4
9
40
400

Complete Example with Class

class RomanConverter:
    def __init__(self):
        self.roman_values = {
            'I': 1, 'V': 5, 'X': 10, 'L': 50, 
            'C': 100, 'D': 500, 'M': 1000
        }
    
    def convert(self, roman_str):
        """Convert Roman numeral string to integer"""
        total = 0
        i = 0
        
        while i < len(roman_str):
            # Check if current character forms subtraction pair with next
            if (i + 1 < len(roman_str) and 
                self.roman_values[roman_str[i]] < self.roman_values[roman_str[i + 1]]):
                total += self.roman_values[roman_str[i + 1]] - self.roman_values[roman_str[i]]
                i += 2
            else:
                total += self.roman_values[roman_str[i]]
                i += 1
        
        return total

# Usage example
converter = RomanConverter()
test_cases = ["III", "IV", "IX", "LVIII", "MCMXC", "CDXLIII"]

for roman in test_cases:
    print(f"{roman} = {converter.convert(roman)}")
III = 3
IV = 4
IX = 9
LVIII = 58
MCMXC = 1990
CDXLIII = 443

Comparison

Method Approach Best For
Dictionary Lookup Pre-defined combinations Clarity and readability
Comparison Compare adjacent characters Memory efficiency
Class-based Object-oriented approach Reusability

Conclusion

Roman to integer conversion can be implemented using dictionary lookup or character comparison methods. The comparison approach is more memory-efficient, while the dictionary method offers better readability for handling subtraction cases.

Updated on: 2026-03-25T07:07:21+05:30

37K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements