classSolution { public: intromanToInt(string s){ int table[256]; table['I'] = 1; table['V'] = 5; table['X'] = 10; table['L'] = 50; table['C'] = 100; table['D'] = 500; table['M'] = 1000; int result = table[s[s.length()-1]]; for(int i = s.length()-2; i >= 0; i--){\ if(table[s[i]] >= table[s[i+1]]){ result += table[s[i]]; }else { result -= table[s[i]]; } } return result; } };
解决方案3(Python)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution(object): defromanToInt(self, s): """ :type s: str :rtype: int """ roman2int = {"I":1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000} result = 0 for index, value in enumerate(s): if index>0and roman2int[value]>roman2int[s[index-1]]: result += (roman2int[value]-2*roman2int[s[index-1]]) else: result += roman2int[value] return result