链接:
https://leetcode-cn.com/problems/roman-to-integer/
题目:
给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
示例 1:
输入: “III” 输出: 3 示例 2:
输入: “IV” 输出: 4 示例 3:
输入: “IX” 输出: 9 示例 4:
输入: “LVIII” 输出: 58 解释: L = 50, V= 5, III = 3. 示例 5:
输入: “MCMXCIV” 输出: 1994 解释: M = 1000, CM = 900, XC = 90, IV = 4.
我的解法:遍历一遍,对应几加上几
class Solution(object):
def romanToInt(self, s):
num = 0
dic = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
for i in range(len(s)):
num += dic[s[i]]
if i>0 and dic[s[i]] > dic[s[i-1]]:
num -= 2*dic[s[i-1]]
return num