Skip to content

Instantly share code, notes, and snippets.

@decagondev
Last active November 7, 2025 21:27
Show Gist options
  • Select an option

  • Save decagondev/85f035194a1b7a97145c9d9a4ddd7d34 to your computer and use it in GitHub Desktop.

Select an option

Save decagondev/85f035194a1b7a97145c9d9a4ddd7d34 to your computer and use it in GitHub Desktop.

Roman to Integer Walkthrough - Step-by-Step Mermaid Visuals


Problem

Convert a Roman numeral string into an integer.

Roman numerals:

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

Rules:

  • Add letters normally: "VI" = 5 + 1 = 6
  • If a smaller letter comes before a larger one: "IV" = 4

Step 1: Letter M

flowchart LR
M["Current: M=1000"]:::add --> C["Next: C=100"]
Total["Total: 0 + 1000 = 1000"]:::add
classDef add fill:#d4f7d4,stroke:#2a7b2a,stroke-width:2px,color:#2a7b2a;
Loading

Step 2: Letter C

flowchart LR
C["Current: C=100"]:::sub --> M["Next: M=1000"]
Total["Total: 1000 - 100 = 900"]:::sub
classDef sub fill:#f7d4d4,stroke:#7b2a2a,stroke-width:2px,color:#7b2a2a;
Loading

Step 3: Letter M

flowchart LR
M["Current: M=1000"]:::add --> X["Next: X=10"]
Total["Total: 900 + 1000 = 1900"]:::add
classDef add fill:#d4f7d4,stroke:#2a7b2a,stroke-width:2px,color:#2a7b2a;
Loading

Step 4: Letter X

flowchart LR
X["Current: X=10"]:::sub --> C["Next: C=100"]
Total["Total: 1900 - 10 = 1890"]:::sub
classDef sub fill:#f7d4d4,stroke:#7b2a2a,stroke-width:2px,color:#7b2a2a;
Loading

Step 5: Letter C

flowchart LR
C["Current: C=100"]:::add --> I["Next: I=1"]
Total["Total: 1890 + 100 = 1990"]:::add
classDef add fill:#d4f7d4,stroke:#2a7b2a,stroke-width:2px,color:#2a7b2a;
Loading

Step 6: Letter I

flowchart LR
I["Current: I=1"]:::sub --> V["Next: V=5"]
Total["Total: 1990 - 1 = 1989"]:::sub
classDef sub fill:#f7d4d4,stroke:#7b2a2a,stroke-width:2px,color:#7b2a2a;
Loading

Step 7: Letter V

flowchart LR
V["Current: V=5"]:::add
Total["Total: 1989 + 5 = 1994"]:::add
classDef add fill:#d4f7d4,stroke:#2a7b2a,stroke-width:2px,color:#2a7b2a;
Loading

Step 8: JavaScript Implementation

function romanToInt(s) {
  const romanMap = { 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 = romanMap[s[i]];
    let next = romanMap[s[i + 1]];
    let action = current < next ? "subtract" : "add";

    if (action === "subtract") {
      total -= current;
      console.log(`\x1b[31mStep ${i+1}: ${s[i]} -> subtract ${current} -> Total=${total}\x1b[0m`);
    } else {
      total += current;
      console.log(`\x1b[32mStep ${i+1}: ${s[i]} -> add ${current} -> Total=${total}\x1b[0m`);
    }
  }

  return total;
}

romanToInt("MCMXCIV");

Step 9: Table Summary

Step Letter Next Action Total
1 M C +1000 1000
2 C M -100 900
3 M X +1000 1900
4 X C -10 1890
5 C I +100 1990
6 I V -1 1989
7 V - +5 1994
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment