The problem is as follows:
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
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.
Here is how I solved it:
- Let's make use of a dictionary to map each roman numeral to its integer value.
- Initialize a variable result to 0, which we will use to store the final integer value.
roman_numbers = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}
result = 0
- Iterate through the string.
- If current character is greater than previous character, subtract twice the value of "s[char - 1]" and add the value of "s[char]". Here is where we handle the subtraction cases.
For example,
IV = 4
(I=1
is less thanV=5
, so add5
and subtract1
twice:5 - 2 + 1
. - Else, add the value of "s[char]" to the result. Here is where we handle the regular addition.
- Return result, which is the integer value of the roman numeral.
for char in range(len(s)):
if char > 0 and roman_numbers[s[char]] > roman_numbers[s[char - 1]]:
result += roman_numbers[s[char]] - 2 * roman_numbers[s[char - 1]]
else:
result += roman_numbers[s[char]]
return result
Here is the completed solution:
class Solution:
def romanToInt(self, s: str) -> int:
roman_numbers = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}
result = 0
for char in range(len(s)):
if char > 0 and roman_numbers[s[char]] > roman_numbers[s[char - 1]]:
result += roman_numbers[s[char]] - 2 * roman_numbers[s[char - 1]]
else:
result += roman_numbers[s[char]]
return result
Top comments (0)