- Reference
- μκ°λ³΅μ‘λ: O(N)
- Runtime
52ms
- Beats
20.24%
- μ§μ§ μ΄λ κ²λ°μ λͺ» νκ² λ€..
- Another Solution 무쑰건 νμν΄μ κ°μ΄ μ¬λ¦Ό
Solution
class Solution:
# λ‘λ§μ μμΈ: 4, 9, 40, 90, 400, 900
# ex) IX: 1 + 8 = 9 -> Xκ° μλ 10μΈλ° -2λ¨κ³κ° λ κ°μΈ 8λ‘ μ²λ¦¬κ° λ¨
# μμ κ°μ κ·μΉ μ΄μ©
def romanToInt(self, s: str) -> int:
sum_value = 0
before_symbol = ''
for i in range(len(s)):
current_symbol = s[i]
# μμ μ¨λμ μμΈ μ²λ¦¬ (-2λ¨κ³)
if before_symbol == 'I' and current_symbol == 'V':
sum_value += 3
elif before_symbol == 'I' and current_symbol == 'X':
sum_value += 8
elif before_symbol == 'X' and current_symbol == 'L':
sum_value += 30
elif before_symbol == 'X' and current_symbol == 'C':
sum_value += 80
elif before_symbol == 'C' and current_symbol == 'D':
sum_value += 300
elif before_symbol == 'C' and current_symbol == 'M':
sum_value += 800
# νμ¬ λ‘λ§ λ¬Έμ λ€ λν΄μ£ΌκΈ°
elif current_symbol == 'I':
sum_value += 1
elif current_symbol == 'V':
sum_value += 5
elif current_symbol == 'X':
sum_value += 10
elif current_symbol == 'L':
sum_value += 50
elif current_symbol == 'C':
sum_value += 100
elif current_symbol == 'D':
sum_value += 500
elif current_symbol == 'M':
sum_value += 1000
# νμ¬ λ¬Έμκ° μ΄μ λ¬Έμκ° λκ³ , λ€μ λ°λ³΅ λ νμ¬ λ¬Έμκ° κ°±μ λ¨
before_symbol = current_symbol
return sum_value
Another Solution
class Solution:
def romanToInt(self, s: str) -> int:
translations = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
}
s = s.replace("IV", "IIII").replace("IX", "VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
number = 0
for char in s:
number += translations[char]
return number
Leave a comment