Roman to Integer

Question

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

Example

IV -> 4

XII -> 12

XXI -> 21

XCIX -> 99

Thoughts

additive notation, VII = 5 + 1 + 1 subtractive notation, IV, 因为小的I出现在了V之前,我们知道了这是subtractive notation, 之前已经加上了1, 所以要减去两个1

Solution

class Solution:
    # @param {string} s Roman representation
    # @return {int} an integer
    def romanToInt(self, s):
        # Write your code here
        map = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }

        if not s:
            return 

        result = 0
        prev = 0
        for i in range(len(s)):
            curr = map[s[i]]
            if prev < curr:
                result += curr - 2 * prev
            else:
                result += curr
            prev = curr

        return result