Easy Coding Problem: Roman to Integer
This problem requires converting a Roman numeral string, represented by seven symbols (I, V, X, L, C, D, and M), into its equivalent integer from 1 to 3999.
Roman numeral values are simple: 1 is I, 2 is II, and 3 is III. Generally, the same character is not repeated four times; hence, the value for 4 is not IIII but IV, which represents 5-1, as V is 5.
Here is a simple list of Roman numerals:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000The subtraction rule for Roman numerals:
- I can be placed before V(5) and X(10) to make 4 and 9.
- X can be placed before L(50) and C(100) to make 40 and 90.
- C can be placed before D(500) and M(1000) to make 400 and 900.
So the easiest way to solve this problem is to understand that if you can compare the numbers next to each other, then you can decide when to apply the subtraction rule.
Get Nitin Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
There are two solutions: first, read the string from back to front, and if a larger number appears once before in the loop, consider the smaller number negative. Second is to just compare the number in the list from front to back with its neighbor, and if the number is smaller, multiply its value by -1 in the calculation. Both solutions has time complexity: O(n) and space complexity: O(1)
First Solution
In this solution, reading the string from the back let ease to change the value of the corresponding roman number to negative from positive, but the code is long, and long code is an unoptimized solution
class Solution:
def romanToInt(self, s: str) -> int:
r = s[::-1]
a = 0
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
A = ['I','V','X','L','C','D','M']
for b in r:
if b in A[1:]:
roman_dict["I"] = -1
if b in A[2:]:
roman_dict["V"] = -5
if b in A[3:]:
roman_dict["X"] = -10
if b in A[4:]:
roman_dict["L"] = -50
if b in A[5:]:
roman_dict["C"] = -100
if b in A[6:]:
roman_dict["D"] = -500
a += roman_dict[b]
return a
if __name__ == "__main__":
# Read a Roman numeral from standard input and display its integer value.
roman = input().strip()
print(Solution().romanToIntShort(roman))
Second solution:
The second solution is based on a better understanding of the subtraction rule. There are only six cases: IV, IX, XL, XC, CD, and CM, where the subtraction rule is applied. It can be seen from these examples that the left value is smaller than the right. Hence, a compression of neighbors is the solution we need.
class Solution:
def romanToIntShort(self, s: str) -> int:
# Create a dictionary to map Roman numerals to their integer values.
roman_dict = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
# Initialize the total to zero.
total = 0
# Iterate through the string, except for the last character.
for i in range(len(s) - 1):
# If the current numeral is less than the next one, subtract it from the total.
if roman_dict[s[i]] < roman_dict[s[i + 1]]:
total -= roman_dict[s[i]]
else:
# Otherwise, add it to the total.
total += roman_dict[s[i]]
# Add the value of the last numeral to the total.
total += roman_dict[s[-1]]
return total
if __name__ == "__main__":
# Read a Roman numeral from standard input and display its integer value.
roman = input().strip()
print(Solution().romanToIntShort(roman))




