본문 바로가기
코딩 공부

Leetcode: 13. Roman to Integer - Python

by 카우보이연구소 2022. 2. 8.

요즘에는 개발자들이 회사에 취업하기 위해서 사용한다는 리트코드 (leetcode) 사이트의 문제들을 풀어보고 있습니다. 이제 막 시작한 초보자라 힘든 점이 많아서 이렇게 글로 남겨서 복습하려고 합니다.

 

문제: Roman to Integer

등급: Easy

내용: 로마 숫자를 일반 숫자로 바꾼다.

<코드>

class Solution(object):
    def romanToInt(self, s):
        answer = 0
        i = 0
        s = s[::-1]
        
        while i < len(s):
            if s[i] == 'I':
                answer += 1
                i += 1
                continue
            if s[i] == 'V':
                answer +=5
                i += 1
                if i < len(s) and s[i] == 'I':
                    answer -= 1
                    i += 1
                continue
            if s[i] =='X':
                answer += 10
                i += 1
                if i < len(s) and s[i] == 'I':
                    answer -= 1
                    i += 1
                continue
            if s[i] == 'L':
                answer += 50
                i += 1 
                if i < len(s) and s[i] == 'X':
                    answer -= 10
                    i += 1
                continue
            if s[i] == 'C':
                answer += 100
                i += 1
                if i < len(s) and s[i] == 'X':
                    answer -= 10
                    i += 1
                continue
            if s[i] == 'D':
                answer += 500
                i += 1
                if i < len(s) and s[i] == 'C':
                    answer -= 100
                    i += 1
                continue
            if s[i] == 'M':
                answer += 1000
                i += 1
                if i < len(s) and s[i] == 'C':
                    answer -= 100
                    i += 1
        return answer

<논리>

굉장히 간단한 코드이다. 딱히 큰 생각이 들어가지 않은 코드로, 주어진 로마 숫자를 뒤집어서 하나씩 더해가는 방식. if가 많은 이유는 앞에 'C', 'I' 같은게 들어가면 또 그만큼을 빼야하기 떄문 ex) 'IV' == 5

 

이보다 간단한 코드, 당연히 있을 듯 싶다.

 

그래서, discussion을 살펴보았다. 그랬더니, dictionary를 사용하면 방법이 있었다! 내 코드보다 훨씬 간단하게 가능했다.

<dictionary 활용한 코드>

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

훨씬 더 깔끔하다!! 간단하다!!

 

 

<총평 외 comment>

 

Happy coding!

 

댓글