Sitemap
Siddharth

Siddharth

Cool!

ROMAN to integer

3 min readApr 3, 2026

I tried solving Roman to integer in python, it looked pretty hard, but wasnt.

Get Siddharth’s stories in your inbox

Join Medium for free to get updates from this writer.

https://leetcode.com/problems/roman-to-integer/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

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 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.

Given a roman numeral, convert it to an integer.

Solution 1:

  • To start off gave values of 0 to sum and i, which i would be needing later.
  • I used while loop because if i used for loop then the incrementation would be messed up, the while loop case was if i was less than length of s.
  • Then we had to check all the conditions for example we had to check each of i was any of the roman numerals. If the condition matched then we can give its value “I”: Sum += 1.
  • In normal cases we would add i += 1, in special cases like above “XL” would be 40 so we would add i += 2
  • When there were special cases like those we had to check them inside of the main case like if it was “CD” we had to check it inside of “C”
  • Then we return sum
class Solution(object):
def romanToInt(self, s):
sum = 0
i = 0
while i < len(s):
if s[i] == "I":
if i + 1 < len(s) and s[i + 1] == "V":
sum += 4
i += 2
elif i + 1 < len(s) and s[i + 1] == "X":
sum += 9
i += 2
else:
sum += 1
i += 1
elif s[i] == "V":
sum += 5
i += 1
elif s[i] == "X":
if i + 1 < len(s) and s[i + 1] == "L":
sum += 40
i += 2
elif i + 1 < len(s) and s[i + 1] == "C":
sum += 90
i += 2
else:
sum += 10
i += 1
elif s[i] == "L":
sum += 50
i += 1
elif s[i] == "C":
if i + 1 < len(s) and s[i + 1] == "D":
sum += 400
i += 2
elif i + 1 < len(s) and s[i + 1] == "M":
sum += 900
i += 2
else:
sum += 100
i += 1
elif s[i] == "D":
sum += 500
i += 1
elif s[i] == "M":
sum += 1000
i += 1

return sum

Solution 2

--

--