
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 1000For example,
2is written asIIin Roman numeral, just two ones added together.12is written asXII, which is simplyX + II. The number27is written asXXVII, which isXX + 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 asIV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written asIX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(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 <= 15scontains only the characters('I', 'V', 'X', 'L', 'C', 'D', 'M').- It is guaranteed that
sis a valid roman numeral in the range[1, 3999].
class Solution: def romanToInt(self, s: str) -> int: res = 0 nums = { "I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000 } for i in range(len(s)-1): if nums[s[i]] < nums[s[i+1]]: res -= nums[s[i]] else: res += nums[s[i]] return res + nums[s[-1]]
단순히 주어진 로마 숫자
s를 아라비아 숫자로 바꿔주면 된다.
예제의
MCMXCIV를 보면,
로마 숫자(이하 로마자)MCMXCIV는 아라비아 숫자(이하 숫자)로1994이다.
1994는 자리수대로 쪼갰을 때, 1, 9, 9, 4 이렇게 봤을 때 뒤로갈수록 규칙이 존재하지 않지만 로마자MCMXCIV같은 경우 단위로 쪼갰을 때 M(1000), CM(900), XC(90), IV(4) 이렇게 뒤로 갈수록 숫자가 작아지는 규칙이 있다.
그래서 그냥 로마자를 숫자로 바꿔서 더해주기만 하면 되는데, 문제는IV,IX,CM과 같은 숫자는IV = V - I이기 때문에 앞에 붙어있는 것을 빼주어야 한다는 것이다. 로마 숫자에서는 뒤로 갈수록 숫자가 작아지는데,IV,IX,CM과 같은 숫자는 숫자가 커진다(IV에서V는I보다 크다).
이런 경우만 잘 보고 풀면 된다.