4、罗马数字转整数 leetcode 13

2020-04-01  本文已影响0人  九答

题目描述

description.png

思路:把所有字符相加,再单独把前一位比后一位小的拿出来,减去2倍差值即可。
先建立一个dict,然后n>0时相减

class Solution:
    def romanToInt(self, s: str) -> int:
        dict={'I':1,'V':5,'X':10,'L':50,
              'C':100,'D':500,'M':1000,}
        
        result = 0
        for n in range(len(s)):
            if n>0 and dict[s[n]] > dict[s[n-1]]:
                result = result + dict[s[n]]-2*dict[s[n-1]]
            else:
                result = result + dict[s[n]]
        return result
上一篇 下一篇

猜你喜欢

热点阅读