Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$
  • Runtime 52ms
  • Beats 20.24%
  • ์ง„์งœ ์ด๋ ‡๊ฒŒ๋ฐ–์— ๋ชป ํ’€๊ฒ ๋‹ค..
    • Another Solution ๋ฌด์กฐ๊ฑด ํ•„์š”ํ•ด์„œ ๊ฐ™์ด ์˜ฌ๋ฆผ


Solution

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 Solution

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