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.
Before diving into the code, let's understand how Roman numerals work:
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 }
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:
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
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.
The above is the detailed content of LeetCode: Roman Numeral to Integer. For more information, please follow other related articles on the PHP Chinese website!