LeetCode 13 Roman to Integer
难度:easy
代码:
# -*- coding: utf-8 -*-
# @File : leet_13.py
# @Author: FanyFull
# @Date : 2021/9/25
class Solution:
def romanToInt(self, s: str) -> int:
roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
prenum = roman_dict[s[0]]
num = 0
for i in range(1, len(s)):
single_num = roman_dict[s[i]]
if prenum < single_num:
num = num - prenum
else:
num = num + prenum
prenum = single_num
num = num + prenum
return num
if __name__ == '__main__':
solution = Solution()
input = 'MCMXCIV'
output = solution.romanToInt(input)
print(output)
这道题的思想也可以说是加减交替吧,之所以说“也”,是因为最近上计算机组成原理也提到过这个说法。
LeetCode 13 Roman to Integer
http://fanyfull.github.io/2021/09/25/LeetCode-13-Roman-to-Integer/