leetcode: 13. Roman to Integer

来源:互联网 发布:小说淘宝网免费阅读 编辑:程序博客网 时间:2024/05/29 03:44

Problem

# Given a roman numeral, convert it to an integer.## Input is guaranteed to be within the range from 1 to 3999.

AC

class Solution():    def romanToInt(self, x):        roman = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}        sum = 0        for i in range(len(x) - 1):            sum += roman[x[i]] if roman[x[i]] >= roman[x[i+1]] else -roman[x[i]]        return sum + roman[x[-1]]if __name__ == "__main__":    assert Solution().romanToInt("IIVX") == 5    assert Solution().romanToInt("MMMCMXCIX") == 3999
原创粉丝点击