문제

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer.

 

Example 1:

Input: s = "III"
Output: 3
Explanation: III = 3.

Example 2:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 3:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

 

Constraints:

  • 1 <= s.length <= 15
  • s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
  • It is guaranteed that s is a valid roman numeral in the range [1, 3999].

코드

class Solution:
    SYMBOL_MAP = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000,
        "IV": 4,
        "IX": 9,
        "XL": 40,
        "XC": 90,
        "CD": 400,
        "CM": 900,
    }

    def romanToInt(self, s: str) -> int:
        res = 0

        cursor = 0
        while cursor < len(s):
            single_s = s[cursor]
            double_s = s[cursor : cursor + 2]

            if double_s in self.SYMBOL_MAP:
                res += self.SYMBOL_MAP[double_s]
                cursor += 2
            else:
                res += self.SYMBOL_MAP[single_s]
                cursor += 1

        return res

해설

  • 먼저 symbol을 integer로 변환하기 위한 SYMBOL_MAP을 생성한다.
  • symbol을 integer로 변환한 값을 저장하기 위한 res 변수와 현재 s의 위치를 가리키는 cursor 변수를 생성한다.
  • 현재 cursor로부터 단일 글자와 두 글자짜리 문자열을 사용하고
    • 만약 두 글자 symbol("IV", "IX"와 같이 뺄셈을 사용하여 나타내는 symbol)에 속하는 경우 해당 값을 res에 더하고 cursor를 두 칸만큼 이동시킨다.
    • 만약 한 글자 symbol에 속하는 경우 해당 값을 res에 더하고 cursor를 한 칸만 이동시킨다.
  • cursor가 s의 모든 글자를 돌면 res 값을 반환한다.
복사했습니다!