산타는 없다

[리트코드 / LeetCode] 8. String to Integer (atoi) 풀이 - python3 본문

코딩테스트/리트코드

[리트코드 / LeetCode] 8. String to Integer (atoi) 풀이 - python3

LEDPEAR 2021. 1. 1. 18:56
반응형

문제 원문

Implement atoi which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
Note:
Only the space character ' ' is considered a whitespace character.Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³¹,  2³¹− 1]. If the numerical value is out of the range of representable values, 2³¹− 1 or −2³¹is returned.
 
Example 1:
Input: str = "42" Output: 42

Example 2:
Input: str = " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.

Example 3:
Input: str = "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:
Input: str = "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:
Input: str = "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−2³¹) is returned.
 
Constraints:
0 <= s.length <= 200s consists of English letters (lower-case and upper-case), digits, ' ', '+', '-' and '.'.

코드 원문

class Solution:
    def myAtoi(self, s: str) -> int:

풀이

입력받은 문자열에서 숫자를 추출하는 문제입니다. 파이썬으로 작성하였습니다.

입력값에서 앞에 공백을 제외하고 처음 만나는 단어?가 숫자일 때 그 숫자를 파싱 하며 해당 단어 이후의 값은 모두 무시합니다.

주의할 점은 +와 -는 숫자로 취급해야하는 점과 -일 때 결과를 음수로 반환해야 하는 점

마지막으로 -2³¹ ~ 2³¹- 1 범위를 초과하는 값은 초과하는 값에 따라 -2³¹ 또는 2³¹− 1로 반환해야 하는 점입니다. 

성공 코드

class Solution:
    def myAtoi(self, s: str) -> int:
        s.lstrip()
        num = 0
        Negative = False
        pos = 0
        for i in s :
            if i == ' ' and pos == 0 :
                s.lstrip()
                continue
            elif (i == '+' or i == '-') and pos == 0 :
                if i == '-' : Negative = True
                if pos == 0 : pos += 1
            elif '0' <= i <= '9':
                num *= 10
                num += int(i)
                if pos == 0 : pos += 1
            else :
                break
            

        if Negative:
            num *= -1

        if num > 2**31 - 1 : num = 2**31 - 1
        elif num < -2**31 : num = -2**31

        return num

결과

Runtime: 28 ms, faster than 93.36% of Python3 online submissions for String to Integer (atoi).

Memory Usage: 14.2 MB, less than 44.06% of Python3 online submissions for String to Integer (atoi).

반응형
Comments