LeetCode - Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Input format is 'String'
---------------------------------------------------------------------------------------------------------
Sample Input: 'XXVII'
Output : 27
------------------------------------------------------------------------------------------------------------
Input is guaranteed to be within the range from 1 to 3999.
Input format is 'String'
---------------------------------------------------------------------------------------------------------
Sample Input: 'XXVII'
Output : 27
------------------------------------------------------------------------------------------------------------
def romanToInt(self, num):
dic = {'I': 1, 'V': 5, 'X': 10, 'L':50, 'C':100, 'D': 500, 'M': 1000}
l = len(num)
integer = dic[num[l-1]]
for i in range(l-1,0,-1):
if dic[num[i]] <= dic[num[i-1]]:
integer += dic[num[i-1]]
else:
integer -= dic[num[i-1]]
return integer
Comments
Post a Comment