Roman to Integer Explained
Problem Statement
Given a Roman numeral string s, convert it to an integer. Roman numerals use symbols I (1), V (5), X (10), L (50), C (100), D (500), and M (1000), with subtraction rules for cases like IV (4) and IX (9). This problem tests your ability to parse strings and handle special cases in numeral systems.
Example
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4, so 1000 + 900 + 90 + 4 = 1994.
Code
Java
Python
JavaScript
public class Solution {
public int romanToInt(String s) {
Map map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int result = 0;
for (int i = 0; i < s.length(); i++) {
if (i < s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
result -= map.get(s.charAt(i));
} else {
result += map.get(s.charAt(i));
}
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.romanToInt("MCMXCIV")); // 1994
}
}
def roman_to_int(s):
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
result = 0
for i in range(len(s)):
if i < len(s) - 1 and roman[s[i]] < roman[s[i + 1]]:
result -= roman[s[i]]
else:
result += roman[s[i]]
return result
# Example usage
print(roman_to_int("MCMXCIV")) # 1994
function romanToInt(s) {
const roman = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 };
let result = 0;
for (let i = 0; i < s.length; i++) {
if (i < s.length - 1 && roman[s[i]] < roman[s[i + 1]]) {
result -= roman[s[i]];
} else {
result += roman[s[i]];
}
}
return result;
}
// Example usage
console.log(romanToInt("MCMXCIV")); // 1994
Explanation
- Create a mapping of Roman symbols to their integer values.
- Iterate through the string from left to right.
- If the current symbol’s value is less than the next, subtract it (e.g., IV = -1 + 5).
- Otherwise, add its value to the result.
- Return the final sum.
Note
The time complexity is O(n), where n is the string length. Ensure the input is a valid Roman numeral to avoid incorrect results.
