Published:
Updated:

  • Reference
  • μ‹œκ°„λ³΅μž‘λ„: O(N)
  • Runtime 52ms
  • Beats 20.24%
  • μ§„μ§œ μ΄λ ‡κ²Œλ°–μ— λͺ» ν’€κ² λ‹€..
    • Another Solution 무쑰건 ν•„μš”ν•΄μ„œ 같이 올림


SolutionPermalink

class Solution:
    # 둜마자 μ˜ˆμ™Έ: 4, 9, 40, 90, 400, 900
    # ex) IX: 1 + 8 = 9 -> Xκ°€ μ›λž˜ 10인데 -2단계가 된 값인 8둜 μ²˜λ¦¬κ°€ 됨
    # μœ„μ™€ 같은 κ·œμΉ™ 이용
    def romanToInt(self, s: str) -> int:
        sum_value = 0
        before_symbol = ''

        for i in range(len(s)):
            current_symbol = s[i]
            # μœ„μ— 써놓은 μ˜ˆμ™Έ 처리 (-2단계)
            if before_symbol == 'I' and current_symbol == 'V':
                sum_value += 3
            elif before_symbol == 'I' and current_symbol == 'X':
                sum_value += 8
            elif before_symbol == 'X' and current_symbol == 'L':
                sum_value += 30
            elif before_symbol == 'X' and current_symbol == 'C':
                sum_value += 80
            elif before_symbol == 'C' and current_symbol == 'D':
                sum_value += 300
            elif before_symbol == 'C' and current_symbol == 'M':
                sum_value += 800
            # ν˜„μž¬ 둜마 문자 λ‹€ 더해주기
            elif current_symbol == 'I':
                sum_value += 1
            elif current_symbol == 'V':
                sum_value += 5
            elif current_symbol == 'X':
                sum_value += 10
            elif current_symbol == 'L':
                sum_value += 50
            elif current_symbol == 'C':
                sum_value += 100
            elif current_symbol == 'D':
                sum_value += 500
            elif current_symbol == 'M':
                sum_value += 1000
            # ν˜„μž¬ λ¬Έμžκ°€ 이전 λ¬Έμžκ°€ 되고, λ‹€μŒ 반볡 λ•Œ ν˜„μž¬ λ¬Έμžκ°€ 갱신됨
            before_symbol = current_symbol

        return sum_value

Another SolutionPermalink

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

        s = s.replace("IV", "IIII").replace("IX", "VIIII")
        s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
        s = s.replace("CD", "CCCC").replace("CM", "DCCCC")

        number = 0
        for char in s:
            number += translations[char]
        return number

Leave a comment