0:00 / 0:00

Turn a Roman numeral into a number. Look up each letter's value and add it, unless the next letter is bigger, then subtract it.

▼

The problem

LeetCode 13 (Easy). Roman numerals use seven letters: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000. Letters are usually written largest to smallest and added up, but a smaller letter before a bigger one is subtracted (IV = 4, IX = 9, XL = 40, XC = 90, CD = 400, CM = 900). Given a numeral, return its integer value.

Examples (LeetCode's): "III" → 3, "LVIII" → 58, "MCMXCIV" → 1994; the walkthrough uses "MCMXCIV".

TRY IT ON LEETCODE ▶

The solution

def roman_to_int(s):
    val = {'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 val[s[i]] < val[s[i+1]]:
            total -= val[s[i]]
        else:
            total += val[s[i]]
    return total

Transcript

Roman to Integer. The Romans wrote numbers with seven letters. I is one, V is five, X is ten, L is fifty, C is a hundred, D is five hundred, and M is a thousand. Given a numeral, return its number.

Usually, you just add. I I I is one, plus one, plus one: three. L V I I I is fifty, plus five, plus three: fifty-eight. But a smaller letter before a bigger one gets subtracted. I V isn't six. It's four: five minus one. And I X is nine.

The naive way lists every subtracting pair: I V, I X, X L, X C, C D and C M. At each spot, it checks all six pairs before reading a single letter. It works, but that's six special cases to check.

Here's the trick. Every pair has the same shape: a smaller letter before a bigger one. Just peek at the next letter. If this one is smaller than its neighbour, subtract it. Otherwise, add it. Take I X: subtract one, then add ten. Nine, the same as the pair.

Let's try M C M X C I V. M is bigger than C: add a thousand. C is smaller than M: subtract a hundred, nine hundred. M: add a thousand, nineteen hundred. X is smaller than C: subtract ten, eighteen ninety. C: add a hundred, nineteen ninety. I is smaller than V: subtract one, nineteen eighty-nine. V is last: add five. Nineteen ninety-four.

In code, a small table maps each letter to its value. Start at zero and walk the string. If there's a next letter and it's worth more, subtract this one. Otherwise, add it. At the end, return the total.

Each letter is read once, so the time is order n. The table always holds seven entries, plus one running total, so the space is order one.

Look it up, peek ahead, add or subtract. That's Roman to Integer.