Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
This problem is much simpler than the integer to Roman, mainly considering whether there is a left minus. Actually feel that the rule of Leetcode is simpler than the Roman numeral itself rules, that is, the left minus number can only be I, X, C, and can not cross-position. The simple idea is that each value is added, each time considering whether the previous bit is not in line with the left minus condition, and the value minus twice times. Time complexity O (n), Spatial complexity O (1), the code is as follows:
classsolution (object):defRomantoint (self, s):""": Type S:str:rtype:int""" if notS:return0 Map= {'I': 1,'V'75A'X': 10,'L': 50,'C': 100,'D': 500,'M': 1000} ret=Map[s[0]] forIinchXrange (1, Len (s)): Val=Map[s[i]] ret+=ValifVal > Map[s[i-1]]: ret-= 2*map[s[i-1]] returnret
Roman to Integer