Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:先建立一个对应的dict。注意转换规则中的特例,比如XL (=50-10), IV (=5-1), 也就是说当前的字母如果小于后面的那个,当前这个字母对应的数字取负。
1 class Solution(object): 2 def romanToInt(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 rNum = {‘I‘:1, ‘V‘:5, ‘X‘:10, ‘L‘:50, ‘C‘:100, ‘D‘:500, ‘M‘:1000} 8 size = len(s) 9 if size == 1: 10 return rNum[s[0]] 11 sum = 0 12 for i in range(size): 13 if i < size - 1 and rNum[s[i]] < rNum[s[i+1]]: 14 sum -= rNum[s[i]] 15 else: 16 sum += rNum[s[i]] 17 return sum
原文:http://www.cnblogs.com/lettuan/p/6443465.html