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
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;
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;
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;
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;
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;
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;
flowchart LR
V["Current: V=5"]:::add
Total["Total: 1989 + 5 = 1994"]:::add
classDef add fill:#d4f7d4,stroke:#2a7b2a,stroke-width:2px,color:#2a7b2a;
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 | 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 |