Leetcode 8. String to Integer (atoi) with Python

Alpha, Orderly·2023년 1월 16일
0

leetcode

목록 보기
30/90
post-thumbnail

문제

atoi를 구현하시오

문제가 너무 길어서 원본 들어가서 번역기를 켜시던 직접 보시던 하시는게 좋을듯 합니다.

문제

예시

Input: s = "42"
Output: 42

Input: s = "   -42"
Output: -42

Input: s = "4193 with words"
Output: 4193

Input: s = "+"
Output: 0

Input: s = "word 123"
Output: 0

Input: s = "+-12"
Output: 0

풀이

평범한 파싱 문제인데

문제는 Input이 너무 다양합니다.

그래서 파싱을 할수 있을만한 입력이 들어왔을때 동작만 구현하고

나머지는 try / except 를 통해 0을 리턴하도록 구현했습니다.

class Solution:
    def myAtoi(self, s: str) -> int:
        try:
            if s == "": return 0

            s = s.strip(" ")

            front = 0
            end = len(s)-1
            fv = [chr(x) for x in range(48, 58)] + ['+', '-']
            ev = [chr(x) for x in range(48, 58)]

            while s[front] not in fv:
                return 0
            while s[end] not in ev:
                end -= 1
            s = s[front:end+1]

            ch = ''

            idx = 0

            while s[idx] == '+' or s[idx] == '-':
                ch = s[idx] + ch
                idx += 1

            if idx == len(s): return 0

            if idx > 1: return 0

            while idx < len(s) and s[idx] in ev:
                ch = ch + s[idx]
                idx += 1

            ans = int(ch)

            if ans < -2**31: return -2**31
            if ans > 2**31-1 : return 2**31-1
            return ans
        except:
            return 0
            
profile
만능 컴덕후 겸 번지 팬

0개의 댓글