[LeetCode/Python] 13. Roman to Integer

도니·2025년 9월 14일

Interview-Prep

목록 보기
14/29
post-thumbnail

📌 Problem

[LeetCode] 13. Roman to Integer

📌 Solution

Code

class Solution:
    def romanToInt(self, s: str) -> int:
        roman_to_int = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }

        total = 0
        n = len(s)

        for i in range(n - 1):
            # if current < next, subtract
            if roman_to_int[s[i]] < roman_to_int[s[i + 1]]:
                total -= roman_to_int[s[i]]
            # else, add
            else:
                total += roman_to_int[s[i]]

        # always add last char
        total += roman_to_int[s[-1]]
        return total
profile
Where there's a will, there's a way

0개의 댓글