题意:输入一个罗马数字,把它转化成对应整数
1 class Solution(object): 2 def romanToInt(self,s): 3 d = {‘I‘:1,‘V‘:5,‘X‘:10,‘L‘:50,‘C‘:100,‘D‘:500,‘M‘:1000} #字典记录 4 sum = d[s[len(s)-1]] #这里是从右往左,从左往右也可 5 for i in range(len(s)-1,0,-1): #相邻两个比大小 6 r = d[s[i]] 7 l = d[s[i-1]] 8 if l >= r: #高位在左边,加 9 sum += l 10 else: #高位在右边,减 11 sum -= l 12 return sum 13 if __name__==‘__main__‘: 14 solution = Solution() 15 s = ‘VII‘ 16 print(solution.romanToInt(s))