Roman numerals are an ancient number system that still finds use today. Converting them to regular integers is a common programming challenge. Let's break down a solution that elegantly handles this conversion.
The Roman Numeral System
Before diving into the code, let's understand how Roman numerals work:
- Basic symbols: I (1), V (5), X (10), L (50), C (100), D (500), M (1000)
- Numbers are generally written largest to smallest, left to right
- When a smaller number comes before a larger one, it means subtraction
The Solution
function romanToInteger(str) {
let symbols = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000,
}
let result = 0
for (let i = 0; i < str.length; i++) {
const current = str[i]
const next = str[i + 1]
if (symbols[current] < symbols[next]) {
result -= symbols[current]
} else {
result += symbols[current]
}
}
return result
}
How It Works: Step by Step
1. Symbol Mapping
First, we create an object that maps each Roman numeral to its corresponding integer value. This makes it easy to look up values quickly.
2. Iterating Through the String
We loop through each character in the input string, keeping track of both the current character and the next one.
3. The Core Logic
For each character, we compare its value with the next character's value:
- If the current value is less than the next value, we subtract it (handles cases like IV = 4)
- Otherwise, we add it to our result (handles cases like VI = 6)
Examples
romanToInteger("III") → 3
Each I adds 1 to the resultromanToInteger("IV") → 4
I is subtracted because it's less than VromanToInteger("IX") → 9
I is subtracted because it's less than X
Conclusion
This solution elegantly handles the conversion of Roman numerals to integers by using a simple comparison technique. The code is concise yet powerful enough to handle all valid Roman numeral inputs.
Top comments (0)