Roman to Integer - LeetCode
Can you solve this real interview question? Roman to Integer - 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 tw
leetcode.com
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
|
class Solution:
def romanToInt(self, s: str) -> int:
romans_int = {'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
answer, current = 0, 0
for i in range(1, len(s)):
if romans_int[s[i-1]] >= romans_int[s[i]]:
answer += romans_int[s[i-1]]
else:
answer -= romans_int[s[i-1]]
current = romans_int[s[i]]
last = romans_int[s[len(s)-1]]
if current >= last:
answer += last
else:
answer -= last
if len(s) == 1:
answer = romans_int[s[0]]
return answer
|
cs |
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 242. Valid Anagram (0) | 2023.06.23 |
---|---|
leetcode 392. Is Subsequence (0) | 2023.06.19 |
leetcode 27. Remove Element (0) | 2023.06.19 |
leetcode 744. Find Smallest Letter Greater Than Target (0) | 2023.06.09 |
백준 28074 모비스 (0) | 2023.06.08 |
댓글