- 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