๐Ÿ›๏ธ Roman to Integer โ€“ Mastering a Classic Coding Problem

NatureNature
4 min read


Difficulty: Easy
LeetCode Problem #13

Whether you're prepping for coding interviews or brushing up your algorithm skills, converting Roman numerals to integers is a classic problem worth mastering. Let's walk through the logic, break it down step-by-step, and solve it using PHP, Python, Java, and JavaScript.


๐Ÿ“œ What Are Roman Numerals?

Roman numerals are made up of seven symbols:

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

Generally, symbols are placed from largest to smallest from left to right. But there are six special subtraction cases:

  • I before V or X โ†’ 4 (IV), 9 (IX)

  • X before L or C โ†’ 40 (XL), 90 (XC)

  • C before D or M โ†’ 400 (CD), 900 (CM)


๐Ÿง  Problem Statement

Given a Roman numeral as a string, convert it to an integer.


๐Ÿ” Strategy

  1. Create a mapping of Roman symbols to their values.

  2. Loop through the string:

    • Compare current symbol with the next one.

    • If current >= next โ†’ add it.

    • If current < next โ†’ subtract it.

  3. Sum everything and return the result.


๐Ÿ”Ž Example: "MCMXCIV"

M(1000) + CM(900) + XC(90) + IV(4) = 1994

Detailed Steps:

SymbolCurrentNextActionRunning Total
M1000CAdd 10001000
C100MSubtract 100900
M1000XAdd 10001900
X10CSubtract 101890
C100IAdd 1001990
I1VSubtract 11989
V5-Add 51994

๐Ÿง‘โ€๐Ÿ’ป PHP Code

class Solution {
    function romanToInt($s) {
        $roman = [
            'I'=> 1, 'V'=> 5, 'X'=>10,
            'L'=>50, 'C'=>100, 'D'=>500, 'M'=>1000
        ];
        $length = strlen($s);
        $total = 0;
        for ($i = 0; $i < $length; $i++) {
            $current = $roman[$s[$i]];
            $next = $roman[$s[$i + 1]] ?? 0;
            if ($current >= $next) {
                $total += $current;
            } else {
                $total -= $current;
            }
        }
        return $total;
    }
}

๐Ÿ Python Code

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

โ˜• Java Code

class Solution {
    public int romanToInt(String s) {
        Map<Character, Integer> roman = Map.of(
            'I', 1, 'V', 5, 'X', 10,
            'L', 50, 'C', 100, 'D', 500, 'M', 1000
        );
        int total = 0;
        for (int i = 0; i < s.length(); i++) {
            int current = roman.get(s.charAt(i));
            int next = (i + 1 < s.length()) ? roman.get(s.charAt(i + 1)) : 0;
            if (current >= next) {
                total += current;
            } else {
                total -= current;
            }
        }
        return total;
    }
}

๐ŸŒ JavaScript Code

var romanToInt = function(s) {
    const roman = {
        'I': 1, 'V': 5, 'X': 10,
        'L': 50, 'C': 100, 'D': 500, 'M': 1000
    };
    let total = 0;
    for (let i = 0; i < s.length; i++) {
        let current = roman[s[i]];
        let next = roman[s[i + 1]] || 0;
        if (current >= next) {
            total += current;
        } else {
            total -= current;
        }
    }
    return total;
};

โœ… Edge Cases

InputOutputNotes
"III"31 + 1 + 1
"IV"45 - 1
"IX"910 - 1
"LVIII"5850 + 5 + 3
"MCMXCIV"1994Detailed above

๐Ÿ“ˆ Complexity

  • Time: O(n), where n is the length of the string

  • Space: O(1), constant space for the map


๐ŸŽฏ Final Thoughts

The Roman to Integer problem is not just a string parsing exercise โ€” it teaches you:

  • The power of hash maps

  • Simple greedy algorithms

  • Conditional logic in iterative loops

Understanding this will make future parsing or conversion problems easier to grasp. Add it to your toolkit of interview essentials!


0
Subscribe to my newsletter

Read articles from Nature directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nature
Nature