본문 바로가기
코딩테스트/LeetCode 문제

LeetCode [알고리즘] Roman to Integer

by junjunjun 2021. 12. 22.
반응형

문제

https://leetcode.com/problems/roman-to-integer/

 

Roman to Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

나의 풀이

class Solution:
    def romanToInt(self, s: str) -> int:
        arr = list(s)
        a = []
        result = 0
        for i,n in enumerate(arr):
            if n == 'I':  #1
                if i+1 <len(arr):
                    if arr[i+1] in ['V','X']:
                        result -= 1
                        continue
      
                result += 1
            elif n == 'V': #5
                result +=5
                
            elif n == 'X': #10
                if i+1 <len(arr):
                    if arr[i+1] in ['L','C']:
                        result -= 10
                        continue
                result += 10          
            elif n == 'L': #50
                result +=50    
            elif n == 'C': #100
                if i+1 <len(arr):
                    if arr[i+1] in ['D','M']:
                        result -= 100
                        continue
                result += 100
            elif n == 'D': #500
                result +=500
   
            elif n == 'M': #1000
                result +=1000
        return result

모든 경우를 다 if문 처리해 주었다.

if문이 너무 많아서 가독성이 떨어진다.

다른 사람 풀이

class Solution:
    def romanToInt(self, s):
        roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
        z = 0
        for i in range(0, len(s) - 1):
            if roman[s[i]] < roman[s[i+1]]:
                z -= roman[s[i]]
            else:
                z += roman[s[i]]
        return z + roman[s[-1]]

딕셔너리를 이용해 주었다.

또한 4,9를 제외한 경우에는 무조건 큰 수가 앞에 온다는 것을 이용하여

i 보다 i+1의 로마문자의 수가 더 크면  i의 문자의 수를 빼주었다. ex) IV -> -1 + 5 = 4

그 이외의 경우에는 더해준다.   

for문에 -1을 해준 이유는

만약 문자의 마지막 자리에 IV가 온다고 하면 반복문에서 이미 1을 빼주어 return 시에 5만 더해주면 된다.

 

반응형

'코딩테스트 > LeetCode 문제' 카테고리의 다른 글

LeetCode [알고리즘] Palindrome Number  (0) 2021.12.22
LeetCode [알고리즘] Two Sum  (0) 2021.12.21

댓글