13. 罗马数字转整数
symbolValues = { ‘I’: 1, ‘V’: 5, ‘X’: 10, ‘L’: 50, ‘C’: 100, ‘D’: 500, ‘M’: 1000 }
d = {‘I’: 1, ‘IV’: 3, ‘V’: 5, ‘IX’: 8, ‘X’: 10, ‘XL’: 30, ‘L’: 50, ‘XC’: 80, ‘C’: 100, ‘CD’: 300, ‘D’: 500, ‘CM’: 800, ‘M’: 1000}
class Solution:
def romanToInt(self, s: str) -> int:
# 统一正负,前面的字符加过了,双字符减去前面的。
d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}
return sum(d.get(s[max(i-1, 0):i+1], d[c]) for i, c in enumerate(s))
# max[i-1,0] 处理首元素 i-1 = -1 的情况,d[c] 是默认值,d.get(s[max(i-1, 0):i+1], d[c]),处理双字符的情况。注意 双字符的值已经考虑前面字符加过的情况。
# 考虑正负,单独加减。
sv = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 }
return sum(sv[c]*(-1) if i+1 < len(s) and sv[c] < sv[s[i+1]] else sv[c] for i, c in enumerate(s))
map = {‘I’: 1, ‘IV’: 4, ‘V’: 5, ‘IX’: 9, ‘X’: 10, ‘XL’: 40, ‘L’: 50, ‘XC’: 90, ‘C’: 100, ‘CD’: 400, ‘D’: 500, ‘CM’: 900, ‘M’: 1000}
遍历 s,如果双字符在 map 中,则将其值加到 ans,并后移 2 位。不在将当前字符值加到 ans,后移 1 位,最后返回 ans。
class Solution:
def romanToInt(self, s: str) -> int:
map = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL': 40, 'L': 50, 'XC': 90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000}
ans, n, i = 0, len(s), 0
while i < n:
if i+1 < n and s[i:i+2] in map:
ans += map[s[i:i+2]]
i += 2
else:
ans += map[s[i]]
i += 1
return ans
SYMBOL = { ‘I’: 1, ‘V’: 5, ‘X’: 10, ‘L’: 50, ‘C’: 100, ‘D’: 500, ‘M’: 1000 }
class Solution:
def romanToInt(self, s: str) -> int:
SYMBOL = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000,}
ans, n = 0, len(s)
for i in range(1, n):
v = SYMBOL[s[i-1]]
ans += v*(-1) if v < SYMBOL[s[i]] else v
return ans + SYMBOL[s[-1]]