#13

Roman to Integer

Easy Look-ahead

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Convert a Roman numeral (I, V, X, L, C, D, M with subtractive pairs like IV and CM) to an integer.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: turn Roman numerals into a number.

Why this works: add each symbol, except when a smaller symbol comes before a bigger one (IV, IX, XL…), then subtract it.

Example: "MCMXCIV"

M +1000, C<M -100, M +1000, X<C -10, C +100, I<V -1, V +5= 1994

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Hard-coding all six subtractive pairs with many if-statements — the "smaller before larger" rule covers them all.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(1).
Topic: Strings
🎬 Episodes 16–20: video coming soon