class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D': 500, 'M':1000}
ret = 0
last = 0
for s in s:
current = roman[s]
if current > last:
ret = ret - 2*last + current
else:
ret += current
last = current
return ret
일단 더하고, 그 뒤에 나오는 값이 최근에 더한 값보다 큰 경우 예외처리를 하도록 만들었다. 특별할 것 없는 코드이다.
class Solution:
def romanToInt(self, s: str) -> int:
# Define the value of each Roman numeral
roman_values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
total = 0
prev_value = 0
# Loop through the string in reverse
for char in reversed(s):
current_value = roman_values[char]
# If the current value is less than the previous one, subtract it
if current_value < prev_value:
total -= current_value
else:
# Otherwise, add it
total += current_value
# Update previous value
prev_value = current_value
return total
순서를 바꿔서 단순히 더하거나 빼도록 만들었다. 순서를 바꿈으로써 연산량을 줄였다.
class Solution:
def romanToInt(self, s: str) -> int:
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ret = 0
n = len(s)
for i in range(n):
# 현재 값이 다음 값보다 작으면 뺄셈
if i < n - 1 and roman[s[i]] < roman[s[i + 1]]:
ret -= roman[s[i]]
else:
ret += roman[s[i]]
return ret
prev_value
or last
변수를 사용하지 않고 처음 선언한 dictionary만 사용한다. 연산량을 줄이는 건 다른 사람의 풀이와 같다.
거꾸로 가는 방식을 생각해내는 데 아직 익숙치 않은 것 같다.
last
와 같은 변수가 정말 필요한지 고민하고 작성해보자.