Description:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
For example, 2
is written as II
in Roman numeral, just two ones added together. 12
is written as XII
, which is simply X + II
. The number 27
is written as XXVII
, which is XX + V + II
.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII
. Instead, the number four is written as IV
. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX
. There are six instances where subtraction is used:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Examples:
Example 1:
Input: s = "III"
Output: 3
Explanation: III = 3.
Example 2:
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 3:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Solution in Python:
Steps to Solve the Problem:
- Create a Dictionary for Roman Numerals:
- We’ll create a dictionary that maps each Roman numeral to its corresponding integer value.
- Iterate Through the String:
- We’ll iterate through the string
s
from left to right. - We’ll compare each Roman numeral with the next one to decide whether to add or subtract its value.
- We’ll iterate through the string
- Subtraction Rule:
- If a numeral is less than the numeral following it, we subtract its value.
- Otherwise, we add its value.
- Edge Cases:
- Ensure to handle strings with only one character.
- Handle the end of the string correctly to avoid index errors.
class Solution:
def romanToInt(self, s: str) -> int:
# Dictionary to map Roman numerals to their integer values
roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Initialize the total to 0
total = 0
# Iterate through the string
for i in range(len(s)):
# If the current numeral is less than the next one, subtract it
if i + 1 < len(s) and roman_to_int[s[i]] < roman_to_int[s[i + 1]]:
total -= roman_to_int[s[i]]
# Otherwise, add its value to the total
else:
total += roman_to_int[s[i]]
return total
Explanation of the Code:
- Dictionary Setup:
roman_to_int
is a dictionary that holds the integer values for each Roman numeral.
- Initialization:
total
is initialized to 0 to hold the cumulative sum of the integer values.
- Iteration and Condition Check:
- We loop through each character in the string
s
. - For each character, we check if it is less than the next character. If so, we subtract its value from
total
. - If it is not less than the next character or it’s the last character, we add its value to
total
.
- We loop through each character in the string
- Return the Result:
- Finally, we return the computed
total
which represents the integer value of the Roman numeral.
- Finally, we return the computed
This method ensures we handle the Roman numeral rules correctly and efficiently convert the input string to the corresponding integer.
Solution in Javascript:
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
// Object to map Roman numerals to their integer values
const romanToIntMap = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
// Initialize the total to 0
let total = 0;
// Iterate through the string
for (let i = 0; i < s.length; i++) {
// Get the value of the current Roman numeral
const currentVal = romanToIntMap[s[i]];
// Get the value of the next Roman numeral (if there is one)
const nextVal = romanToIntMap[s[i + 1]];
// If the current numeral is less than the next one, subtract it
if (nextVal && currentVal < nextVal) {
total -= currentVal;
} else { // Otherwise, add its value to the total
total += currentVal;
}
}
return total;
};
Solution in Java:
import java.util.HashMap;
import java.util.Map;
class Solution {
public int romanToInt(String s) {
// Map to store Roman numerals and their corresponding integer values
Map<Character, Integer> romanToIntMap = new HashMap<>();
romanToIntMap.put('I', 1);
romanToIntMap.put('V', 5);
romanToIntMap.put('X', 10);
romanToIntMap.put('L', 50);
romanToIntMap.put('C', 100);
romanToIntMap.put('D', 500);
romanToIntMap.put('M', 1000);
// Initialize the total to 0
int total = 0;
// Iterate through the string
for (int i = 0; i < s.length(); i++) {
// Get the value of the current Roman numeral
int currentVal = romanToIntMap.get(s.charAt(i));
// Get the value of the next Roman numeral (if there is one)
int nextVal = (i + 1 < s.length()) ? romanToIntMap.get(s.charAt(i + 1)) : 0;
// If the current numeral is less than the next one, subtract it
if (currentVal < nextVal) {
total -= currentVal;
} else { // Otherwise, add its value to the total
total += currentVal;
}
}
return total;
}
}
Solution in C#:
using System;
using System.Collections.Generic;
public class Solution {
public int RomanToInt(string s) {
// Dictionary to map Roman numerals to their integer values
Dictionary<char, int> romanToIntMap = new Dictionary<char, int> {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
// Initialize the total to 0
int total = 0;
// Iterate through the string
for (int i = 0; i < s.Length; i++) {
// Get the value of the current Roman numeral
int currentVal = romanToIntMap[s[i]];
// Get the value of the next Roman numeral (if there is one)
int nextVal = (i + 1 < s.Length) ? romanToIntMap[s[i + 1]] : 0;
// If the current numeral is less than the next one, subtract it
if (currentVal < nextVal) {
total -= currentVal;
} else { // Otherwise, add its value to the total
total += currentVal;
}
}
return total;
}
}