LeetCode – 13. Roman to Integer(EASY)

題目連結 : Roman to Integer – LeetCode

Python
class Solution:
    def romanToInt(self, s: str) -> int:
        sum = 0
        

        for i in range(len(s)-1):
            if s[i] == 'I' and s[i+1] == 'V':
                sum = sum -1
            elif s[i] == 'I' and s[i+1] == 'X':
                sum = sum -1
            elif s[i] == 'X' and s[i+1] == 'L':
                sum = sum -10
            elif s[i] == 'X' and s[i+1] == 'C':
                sum = sum -10
            elif s[i] == 'C' and s[i+1] == 'D':
                sum = sum -100
            elif s[i] == 'C' and s[i+1] == 'M':
                sum = sum -100
            elif s[i] == 'M':
                sum = sum + 1000
            elif s[i] == 'D':
                sum = sum + 500
            elif s[i] == 'C':
                sum = sum + 100
            elif s[i] == 'L':
                sum = sum + 50
            elif s[i] == 'X':
                sum = sum + 10
            elif s[i] == 'V':
                sum = sum + 5    
            elif s[i] == 'I':
                sum = sum + 1
       
        # 加上最後一個字符的值
        sum = sum + self.roman_char_to_int(s[-1])

        return sum

    def roman_char_to_int(self, char: str) -> int:
        if char == 'M':
            return 1000
        elif char == 'D':
            return 500
        elif char == 'C':
            return 100
        elif char == 'L':
            return 50
        elif char == 'X':
            return 10
        elif char == 'V':
            return 5
        elif char == 'I':
            return 1
        else:
            return 0
Python
class Solution:
    def romanToInt(self, s: str) -> int:
        roman_values = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}
        roman_sum = 0

        for i in range(len(s) - 1):
            if roman_values[s[i]] < roman_values[s[i + 1]]:
                roman_sum -= roman_values[s[i]]
            else:
                roman_sum += roman_values[s[i]]

        # 加上最後一個字符的值
        roman_sum += roman_values[s[-1]]

        return roman_sum