https://leetcode-cn.com/problems/roman-to-integer/
代码:
# -*- coding:utf-8 -*-
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
alpha_num_dict = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
sum = 0
for i in range(len(s)):
if i < len(s) - 1 and alpha_num_dict[s[i]] < alpha_num_dict[s[i + 1]]:
sum -= alpha_num_dict[s[i]]
else:
sum += alpha_num_dict[s[i]]
return sum
if __name__ == '__main__':
s = 'IV'
print(Solution().romanToInt(s))
思路:这道题也是蛮简单的,直接遍历字符串s,如果前一位比后一位小则做减法,反之加法。
0 条评论