로마자에서 숫자로 바꾸기 1~3999 사이의 로마자 s를 인자로 주면 그에 해당하는 숫자를 반환해주세요.
로마 숫자를 숫자로 표기하면 다음과 같습니다.
def roman_to_num(string):
a = {}
b = "d"
result = 0
a["I"] = 1
a["V"] = 5
a["X"] = 10
a["L"] = 50
a["C"] = 100
a["D"] = 500
a["M"] = 1000
for x in string:
result += a[x]
if b[-1] == "I":
if x == "V" or x == "X":
result -= 2
elif b[-1] == "X":
if x == "L" or x == "C":
result -= 20
elif b[-1] == "C":
if x == "D" or x == "M":
result -= 200
b += x
return result
#solution1
# def roman_to_num(s):
# """
# :type s: str
# :rtype: int
# """
# L = []
# sum = 0
# d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
# for i in s[::-1]:
# if L:
# if i=='I' and L[-1] in ['V','X']:
# sum -= 1
# L.pop()
# elif i=='X' and L[-1] in ['L','C']:
# sum -= 10
# L.pop()
# elif i=='C' and L[-1] in ['D','M']:
# sum -= 100
# L.pop()
# else:
# sum += d[i]
# L.append(i)
# else:
# sum +=d[i]
# L.append(i)
# return sum
#solution2
numbers = {
"I" : 1,
"IV" : 4,
"V" : 5,
"IX" : 9,
"X" : 10,
"XL" : 40,
"L" : 50,
"XC" : 90,
"C" : 100,
"CD" : 400,
"D" : 500,
"CM" : 900,
"M" : 1000,
}
def roman_to_num(s):
if not s:
return 0
if numbers.get(s[:2]):
return numbers.get(s[:2]) + roman_to_num(s[2:])
return numbers.get(s[:1]) + roman_to_num(s[1:])