ROMAN to integer
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,DandM.Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000For example,
2is written asIIin Roman numeral, just two ones added together.12is written asXII, which is simplyX + II. The number27is written asXXVII, which isXX + 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 asIV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asIX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.
Xcan be placed beforeL(50) andC(100) to make 40 and 90.
Ccan be placed beforeD(500) andM(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 sumSolution 2







