Input: s = "III"
Output: 3
Explanation: III = 3.
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
class Solution:
def romanToInt(self, s: str) -> int:
dict = {"I":1, "IV":4, "V":5, "IX":9, "X":10, "XL":40, "L":50, "XC":40, "C":100, "CD":400, "D":500, "CM":900, "M":1000}
answer = 0
for idx, value in enumerate(s):
answer += dict[value]
if idx > 0 and idx < len(s) and s[idx-1]+s[idx] in dict:
answer -= 2 * dict[s[idx-1]]
return answer
해당 문제의 예외는, 4(IV),9(IX), 40(XL)과 같은 앞에 작은 수가 나오고 두 개의 문자로 되어있는 수 들이었다.
그래서 나는 dict안에 넣어버렸다. 그리고, 해당 조건이 만족하면, 수를 빼기로 했다. 2를 곱한건 그 위에 한번 넣어줬기 때문에, 두번 빼주는것이다.