The Roman to Integer problem asks you to take a string written in Roman numerals and convert it into an integer value. Roman numerals were used in ancient Rome and are composed of letters representing certain base values. This task involves interpreting those characters correctly and handling specific patterns where subtraction is used instead of addition.
Roman numerals use seven different symbols:
I
= 1V
= 5X
= 10L
= 50C
= 100D
= 500M
= 1000
Normally, these symbols are added from left to right. For example, "VI"
means 5 + 1 = 6.
However, if a smaller symbol appears before a larger one, it is subtracted. For example, "IV"
means 5 - 1 = 4.
The solution involves scanning the input string from left to right while checking each character and the one after it (if it exists). We use a dictionary to map each Roman numeral to its integer value. Then, during the scan:
Consider the input "MCMXCIV"
. We can break it down like this:
M = 1000 CM = 900 (100 before 1000, so subtract) XC = 90 (10 before 100, subtract) IV = 4 (1 before 5, subtract) Total = 1000 + 900 + 90 + 4 = 1994
map = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } sum = 0 i = 0 while i < s.length: if i + 1 < s.length and map[s[i]] < map[s[i+1]]: sum += map[s[i+1]] - map[s[i]] i += 2 else: sum += map[s[i]] i += 1 return sum
n
is the length of the input string.To convert a Roman numeral to an integer, we loop through the string while using a simple rule: subtract if the current numeral is smaller than the next; otherwise, add it. This approach covers all valid Roman numeral strings and runs efficiently in linear time.