이 문제에서는 로마자 숫자를 10진수의 숫자로 변경하는 프로그램을 짜야한다.
문제 풀이
로마자를 어떤 숫자로 변환해야 하는지는 이미 조건으로 주어졌다.
단, 다음의 경우에 대해서는 예외처리는 해주어야 한다.
{"IV" : 4, "IX" : 9, "XL" : 40, "XC" : 90, "CD" : 400, "CM" : 900}
문자열을 순회하면서 현재의 index가 맨 마지막 글자가 아니고 I, X, C 문자라면 그 뒤에 있는 문자에 I일 경우 V, X가 있거나, 문자가 X일 경우에는 L, C가 있거나, 문자가 C일 경우에는 뒤에 문자가 D, M인지를 확인해서 예외처리를 해주면 된다.
파이썬 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
class Solution:
def romanToInt(self, s: str) -> int:
"""
Runtime : faster than 96.31% of Python3
Memory Usage : less than 5.05% of Python3
"""
table = {"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}
is_pass = False
num = 0
for idx, ch in enumerate(s):
if is_pass:
is_pass = False
continue
if idx < len(s) - 1:
if ch == 'I':
next_ch = s[idx + 1]
if next_ch == 'V':
num += 4
is_pass = True
continue
elif next_ch == 'X':
num += 9
is_pass = True
continue
if ch == "X":
next_ch = s[idx + 1]
if next_ch == 'L':
num += 40
is_pass = True
continue
elif next_ch == "C":
num += 90
is_pass = True
continue
if ch == 'C':
next_ch = s[idx + 1]
if next_ch == 'D':
num += 400
is_pass = True
continue
elif next_ch == "M":
num += 900
is_pass = True
continue
num += table[ch]
return num
s = Solution()
s.romanToInt("III") # 3
s.romanToInt("IV") # 4
s.romanToInt("IX") # 9
s.romanToInt("LVIII") # 58
s.romanToInt("MCMXCIV") # 1994
|
cs |
'온라인 코딩 테스트 문제 풀이 > LeetCode 문제 풀이' 카테고리의 다른 글
Python으로 푸는 LeetCode 27. Remove Element (Easy) (0) | 2019.04.04 |
---|---|
Python으로 푸는 LeetCode 26. Remove Duplicates from Sorted Array (Easy) (0) | 2019.04.03 |
Python으로 푸는 LeetCode 9. Palindrome Number(Easy) (0) | 2019.04.01 |
Python으로 푸는 LeetCode 7. Reverse Integer (Easy) (0) | 2019.03.30 |