13. Roman to Integer leetcode Python 2016 new Season

来源:互联网 发布:mac 拷贝隐藏文件 编辑:程序博客网 时间:2024/05/22 06:22

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

O(n) time go through the whole string. O(1) space.

class Solution(object):    def romanToInt(self, s):        """        :type s: str        :rtype: int        """        ROMAN_HASH = {            'M' : 1000,            'D' : 500,            'C' : 100,            'L' : 50,            'X' : 10,            'V' : 5,            'I' : 1            }        total_value = 0        previous_value = 0        for char in s:            current_value = ROMAN_HASH[char]            if previous_value < current_value:                total_value += current_value - 2 * previous_value            else:                total_value += current_value            previous_value = current_value        return total_value        


0 0